【问题标题】:convert the output of PinField.getPassword() to string将 PinField.getPassword() 的输出转换为字符串
【发布时间】:2010-07-27 20:12:47
【问题描述】:
        if ("Submit".equals(cmd)) { //Process the password.
    String UserNameInput=UserName.getText();
    ///////////////////////////////ERROR Pin when printed shows error/////////////////////////////
    char[] PinInput = PinField.getPassword();
    String pinInput=PinInput.toString();
            //for debugging , print PinInput , but it prints garbage
    System.out.println("Pin entered is "+PinInput);
            //pinInput has garabage instead of the Pin that was entered
            //so the function isPasswordCorrect fails to verify UserName & Pin
    if (isPasswordCorrect(UserNameInput,pinInput)) 
              {
               //some tasks
              }
         }
            boolean isPasswordCorrect(String Username,String Pin)
            {
             //verify username & pin 
            }

我需要将 PinInput 从字符数组转换为字符串,以便我可以使用函数 isPasswordCorrect() 。当我使用 toString() 方法时,它会产生垃圾值,我应该怎么做才能转换 PinInput 到 String 的值?

【问题讨论】:

标签: java swing tostring getpasswd


【解决方案1】:

看String API,有一个构造函数接受一个char数组。

【讨论】:

  • 谢谢,我找到了 public String(char[] value)
【解决方案2】:

@camickr 是对的。那不是垃圾。 pinField.getPassword().toString() 显示char[] 的地址,例如[C@fd54d6.

附录:String.valueOf(array)new String(array) 会将getPassword() 的结果转换为String,但这会阻碍返回char[] 的安全优势。考虑将值保持在本地并遵循 API 指南:“建议在使用后通过将每个字符设置为零来清除返回的字符数组。”

【讨论】:

  • 只是询问知识(我得到了答案),有没有办法将该 cha[] 数组转换为字符串?
  • 并且 String.valueOf(array) 方法只使用“new String(array)”。这是一种方便的方法。
猜你喜欢
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-09
  • 2011-01-20
  • 1970-01-01
  • 2022-10-02
相关资源
最近更新 更多