Why getText() in JPasswordField was deprecated?

前端 未结 4 1479
说谎
说谎 2020-11-28 13:13

I never thought before, only I used the method getPassword that returning an array of characters and I had seen the getText method was depr

4条回答
  •  囚心锁ツ
    2020-11-28 13:58

    The reason behind this behavior is the Java String pool (see e.g. this SO question for more info). As soon as you convert the contents of that password field to a String (which is what happens if you use the getText method) the String is placed in the pool, and can be read by others.

    If you would look at the implementation of the getPassword method (as can be seen in the SO question @Garbage posted as a comment on your question) you can see this carefully avoids creating a String.

    Note that this also means you should not do something like

    if ( Arrays.equals( "mySuperSecretPassword".toCharArray(), passwordField.getPassword() ) )
    

    or you still end up with putting the password in the pool, and then you could as easily have used the getText method.

提交回复
热议问题