java反射基本知识和应用

在最近的项目中,在Coding阶段,发现很多代码冗余,代码质量很差,故此研究了一下java的反射,有什么错,请各位大神指出纠正

数据准备:

Person类

public class Person {
	
	private String sex;
	
	private String personId;

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getPersonId() {
		return personId;
	}

	public void setPersonId(String personId) {
		this.personId = personId;
	}

}

 Student类

public class Student extends Person {
	
	public String username;
	
	private int age;
	
	public Student() {
		// TODO Auto-generated constructor stub
	}
	
	private float chineseClz;
	
	private float physicalClz;
	
	private float englishClz;
	
	private float historyClz;
	
	
	
    public String getUsername() {
		return username;
	}



	public void setUsername(String username) {
		this.username = username;
	}



	public int getAge() {
		return age;
	}



	public void setAge(int age) {
		this.age = age;
	}



	public float getChineseClz() {
		return chineseClz;
	}



	public void setChineseClz(float chineseClz) {
		this.chineseClz = chineseClz;
	}



	public float getPhysicalClz() {
		return physicalClz;
	}



	public void setPhysicalClz(float physicalClz) {
		this.physicalClz = physicalClz;
	}



	public float getEnglishClz() {
		return englishClz;
	}



	public void setEnglishClz(float englishClz) {
		this.englishClz = englishClz;
	}



	public float getHistoryClz() {
		return historyClz;
	}



	public void setHistoryClz(float historyClz) {
		this.historyClz = historyClz;
	}



	@SuppressWarnings("unused")
	private int getTotal(int a,int b,int c,int d){
    	return a+b+c+d;
    }

	@Override
	public String toString() {
		return "Student [username=" + username + ", age=" + age
				+ ", chineseClz=" + chineseClz + ", physicalClz=" + physicalClz
				+ ", englishClz=" + englishClz + ", historyClz=" + historyClz
				+ "]";
	}
	
}

 测试类(需要junit.jar)

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {
	
	/**
	 * 获取该类所有的公开方法名
	 */
	@org.junit.Test
	public void test(){
		Class<Student> c=Student.class;
		//获取该class和该class父类所有的公开方法
		Method[] methods=c.getMethods();
		for(Method m:methods){
			/*System.out.println(m);*/
			System.out.println(m.toString());
		}
	}
	
	/**
	 * 获取该类所有的方法名包括[private]
	 */
	@org.junit.Test
	public void test1(){
		Class<Student> c=Student.class;
		//获取该class的所有方法
		Method[] methods=c.getDeclaredMethods();
		for(Method m:methods){
			/*System.out.println(m);*/
			System.out.println(m.toString());
		}
	}
	
	/**
	 * 反射创建对象
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	@org.junit.Test
	public void test2() throws InstantiationException, IllegalAccessException{
		Class<Student> c=Student.class;
		Student stu=(Student)c.newInstance();
		stu.setUsername("Lyncc");
		stu.setAge(11);
		System.out.println(stu.toString());
	}
	
	/**
	 * 获取类中的属性变量
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	@org.junit.Test
	public void test3() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
		Student student=new Student();
		Class<Student> c=Student.class;
		Field usernamField=c.getField("username");
		usernamField.set(student, "Lyncc");
		System.out.println(student.toString());
	}
	
	/**
	 * 获取值
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	@org.junit.Test
	public void test4() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
		Student student=new Student();
		student.setUsername("Lyncc");
		student.setAge(21);
		Class<Student> c=Student.class;
		Field f=c.getDeclaredField("age");
		//private属性必须加
		f.setAccessible(true);
		Object obj=f.get(student);
		System.out.println(obj);
	}
	
	
	/**
	 * 获取该类的制定方法
	 * @throws SecurityException 
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 * @throws NumberFormatException 
	 */
	@org.junit.Test
	public void test5() throws NoSuchMethodException, SecurityException, NumberFormatException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		Student student=new Student();
		Class<Student> c=Student.class;
		Method m=c.getDeclaredMethod("getTotal", new Class[]{int.class,int.class,int.class,int.class});
		m.setAccessible(true);
		Object result=m.invoke(student,new Object[]{new Integer(100),new Integer(100),new Integer(100),new Integer(100)}); 
	    System.out.println(result);
	}
	
	
	/**
	 * 综合实例
	 * 场景:
	 * 前台提交一个表单,例如学生的各科成绩,后台验证数据合理性的时候必须0<getChineseClz<100
	 * 0<getEnglishClz<100等等,如果有一个学生有10门课就必须写10次if的判断,代码很冗余
	 */
	@org.junit.Test
	public void test6() throws NoSuchMethodException, SecurityException, NumberFormatException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		//测试数据
		Student student=new Student();
		student.setChineseClz(97.0f);
		student.setEnglishClz(96.0f);
		student.setHistoryClz(98.5f);
		student.setPhysicalClz(95.4f);
		//传统做法
		/*if(student.getChineseClz()!=0.0f){
			validation(student.getChineseClz());
		}
		if(student.getEnglishClz()!=0.0f){
			validation(student.getEnglishClz());
		}
		if(student.getHistoryClz()!=0.0f){
			validation(student.getHistoryClz());
		}
		if(student.getPhysicalClz()!=0.0f){
			validation(student.getPhysicalClz());
		}*/
		//TODO
		//to do other things
		//反射做法
		Class<Student> c=Student.class;
		Method[] stuMethods=c.getDeclaredMethods();
			for(Method m:stuMethods){
				if(m.toString().indexOf("Clz")>-1&&m.toString().indexOf("get")>-1){
					Object result=m.invoke(student);
					if(validation((float)result)){
						System.out.println("可以保存到数据库");
						//TODO
						//saveDataToDataBase();
					}
				}
			}
	}
	 
	  private boolean validation(float point){
	    	if(0.0f<point&&point<100.0f){
	    		System.out.println("数据正确");
	    		return true;
	    	}else{
	    		System.out.println("数据错误");
	    		return false;
	    	}
	    }

}

 希望有能帮助到大家的地方,谢谢,有什么不对的可鞭策

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值