首页 > 其他 > 详细

使用反射和内省对对象的操作

时间:2014-03-20 15:02:24      阅读:320      评论:0      收藏:0      [点我收藏+]


先定义一个学生类:

类中具备getter、setter

class Student {
	private String name;
	private int age;
	public Student(String s, int a){
		this.name = s;
		this.age = a;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

分别使用反射和内省对对象的操作:

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class IntroSpectorTest {

	public static void main(String[] args) throws Exception {
	
		Student s = new Student("zhangsan", 20);
		Student s1 = new Student("lisi", 20);
		//通过反射获得s的各项值
		Method methodGetName = s.getClass().getMethod("getName");
		String name = (String) methodGetName.invoke(s);
		System.out.println(name);
		//通过内省获得...
		PropertyDescriptor pd = new PropertyDescriptor("name", s.getClass());
		Method methodGetName1 = pd.getReadMethod();
		String name1 = (String) methodGetName1.invoke(s);
		System.out.println(name1);
		
		System.out.println("-----------");
		//继续使用反射对s对象赋值
		Method methodSetNmae = s.getClass().getMethod("setName", String.class);
		methodSetNmae.invoke(s, "lisi");
		System.out.println(s.getName());
		
		//继续使用内省对s对象赋值
		Method methodSetName1 = pd.getWriteMethod();
		methodSetName1.invoke(s1, "zhangsan");
		System.out.println(s1.getName());
		
		System.out.println("-------------");
		//对其他属性操作
		PropertyDescriptor pd1 = new PropertyDescriptor("age", s.getClass());
		Method methodGetAge = pd1.getReadMethod();
		System.out.println(methodGetAge.invoke(s1));
		Method methodSetAge = pd1.getWriteMethod();
		methodSetAge.invoke(s1, 23);
		System.out.println(s1.getAge());
	}
}

两者分别是怎样实现对元素的操作的呢?

反射:

1、获得某类的某个具体操作方法 (通过类.class文件调用方法,并传入方法名和参数获得)

2、使用获得的方法操作属性 (调用得到的方法传入对象以及需要的参数操作属性)

内省:

1、获得某对象的某一属性 (通过传入属性名称,类.class获得相应的属性对象)

2、获得某类的某个具体操作方法 (通过属性对象获得get/set方法)

3、使用获得的方法操作属性 (同反射)





使用反射和内省对对象的操作,布布扣,bubuko.com

使用反射和内省对对象的操作

原文:http://blog.csdn.net/u013610441/article/details/21613953

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!