利用反射验证用户信息是否符合规范
package sixteen;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class yan extends JFrame {
public yan(){
Container cc=getContentPane();
cc.setLayout(null);
setTitle("登入界面");
setSize(500, 400);
setVisible(true);
setDefaultCloseOperation(HIDE_ON_CLOSE);
final JTextField jt1=new JTextField();
final JTextField jt2=new JTextField();
JButton jb1=new JButton("登入");
JButton jb2=new JButton("重置");
JLabel jl1=new JLabel("账号:");
JLabel jl2=new JLabel("密码:");
final JLabel jl3=new JLabel("输入正确");
final JLabel jl4=new JLabel("输入错误");
cc.add(jt1);
cc.add(jt2);
cc.add(jb1);
cc.add(jb2);
cc.add(jl1);
cc.add(jl2);
cc.add(jl3);
jl3.setVisible(false);
jt1.setBounds(150, 70, 300, 50);
jt2.setBounds(150, 170, 300, 50);
jb1.setBounds(200, 280, 60, 40);
jb2.setBounds(280, 280, 60, 40);
jl1.setBounds(100, 80, 40, 50);
jl2.setBounds(100, 180, 40, 50);
jl3.setBounds(150, 240, 300, 30);
jb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new zheng();
}
});
jb2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
jt1.setText("");
jt2.setText("");
jl3.setVisible(false);
}
});
}
public static void main(String[] args) {
new yan();
}
package sixteen;
import java.lang.reflect.Field;
public class zheng {
public static void main(String[] args) {
String xx="\\p{Lower}";
String yy="\\p{Digit}";
yan zz=new yan();
Class c=zz.getClass();
try {
Field t1=c.getDeclaredField("jt1");
Field t2=c.getDeclaredField("jt2");
Field l3=c.getDeclaredField("jl3");
Field l4=c.getDeclaredField("jl4");
try {
if (((String) t1.get(zz)).matches(xx)&&((String) t2.get(zz)).matches(yy)){
l3.set(zz,true);
}
else{
l4.set(zz,true);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}