第16章 反射

利用反射验证用户信息是否符合规范

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();
		} 
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值