在保存之前比较 Java 中的两个 JPasswordFields?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13995986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare two JPasswordFields in Java before saving?
提问by user1922355
Possible Duplicate:
How to check if JPassword field is null
While creating a login registration form, I am using two password fields. Before saving the data, I want to compare both fields; and if they match, then the data should be saved in file. If not it should open a dialog box. Please can anyone help me.
在创建登录注册表时,我使用了两个密码字段。在保存数据之前,我想比较两个字段;如果它们匹配,则数据应保存在文件中。如果不是,它应该打开一个对话框。请任何人都可以帮助我。
回答by Reimeus
The safest way would be to use Arrays.equals:
最安全的方法是使用Arrays.equals:
if (Arrays.equals(passwordField1.getPassword(), passwordField2.getPassword())) {
// save data
} else {
// do other stuff
}
Explanation:JPassword.getText
was purposely deprecated to avoid using Strings
in favor of using a char[]
returned by getPassword
.
说明:JPassword.getText
被故意弃用以避免使用Strings
而支持使用char[]
返回的getPassword
。
When calling getText
you get a String (immutable object) that may not be changed (except reflection) and so the password stays in the memory until garbage collected.
调用时,getText
您会得到一个不能更改的字符串(不可变对象)(反射除外),因此密码会保留在内存中,直到垃圾回收为止。
A char array however may be modified, so the password will really not stay in memory.
然而,一个字符数组可能会被修改,所以密码不会真正留在内存中。
This above solution is in keeping with that approach.
上述解决方案与该方法一致。
回答by David Kroukamp
It would help to show what you have tried...
这将有助于展示您尝试过的内容......
but you'd do it something like:
但你会这样做:
//declare fields
JPasswordField jpf1=...;
JPasswordField jpf2=...;
...
//get the password from the passwordfields
String jpf1Text=Arrays.toString(jpf1.getPassword());//get the char array of password and convert to string represenation
String jpf2Text=Arrays.toString(jpf2.getPassword());
//compare the fields contents
if(jpf1Text.equals(jpf2Text)) {//they are equal
}else {//they are not equal
}