Why does JPasswordField.getPassword() create a String with the password in it?

前端 未结 7 2045
长发绾君心
长发绾君心 2020-11-28 10:52

Swing\'s JPasswordField has the getPassword() method that returns a char array. My understanding of this is that the array can be zeroed immediately after use so that you do

7条回答
  •  野性不改
    2020-11-28 11:41

    The Swing implementation is too complex to check by hand. You want tests.

    public class Pwd {
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new javax.swing.JFrame("Pwd") {{
                        add(new javax.swing.JPasswordField() {
                            @Override public String getText() {
                                System.err.println("Awoooga!!");
                                return super.getText();
                            }
                            {
                                addActionListener(
                                    new java.awt.event.ActionListener() {
                                        public void actionPerformed(
                                            java.awt.event.ActionEvent event
                                        ) {
                                            // Nice.
                                        }
                                    }
                                );
                            }
                        });
                        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
                        pack();
                        setVisible(true);
                    }};
                }
            });
        }
    }
    

    Looks like the command string for the (pointless) action event to me. There will be other way to cause the effect as well.

    A vaguely modern VM will move objects in memory anyway, so clearing the char[] does not necessarily work.

提交回复
热议问题