您的位置:首页 > 编程语言 > Java开发

java 反射初步

2011-11-14 11:58 183 查看
需要操作的对象:

package Reflection;

public class Person {

private int age;
private String name;
private long id;

public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}

}


反射取得数据

package Reflection;

import java.lang.reflect.*;

/**
* 本程序复制一个对象,然后返回一个与此对象一直的对象
*/

public class ReflectTest {

public Object copyObj(Object obj) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException
{
Class<?> classType = obj.getClass();  //取得原来对象的Class引用
System.out.println(classType.getName());   //打印原对象的名称(包括包名)

Object objectCopy =
classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
//通过默认构造函数,创建一个新对象
Field[] fields = classType.getDeclaredFields(); //取得Field[]域的对象
for (Field field : fields)  //分解各个Field
{
String firstDigital = field.getName().substring(0,1); //取得域的首字母
String remainDigital = field.getName().substring(1);  //取得域的其他子目

String getMethodName =
"get" + firstDigital.toUpperCase() + remainDigital; //取得set方法名称
String setMethodName =
"set" + firstDigital.toUpperCase() + remainDigital; //取得get方法名称

Method getMethod =
classType.getDeclaredMethod(getMethodName, new Class[]{}); //返回域get方法

Method setMethod =
classType.getDeclaredMethod(setMethodName, field.getType());//返回与set方法

Object value = getMethod.invoke(obj, new Object[]{});  //用get方法取得原(传入的obj)对象的数据
System.out.println(value);

setMethod.invoke(objectCopy, value);	 //将上面的原数据通过set方法写入到要复制的对象中去

}
return objectCopy;
}

public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
Person p = new Person();
p.setName("Tom");
p.setAge(22);
p.setId(100);

Person personCopy = (Person) new ReflectTest().copyObj(p);

System.out.println("Copy info: " + personCopy.getId() + " " + personCopy.getName() + " "
+ personCopy.getAge());

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: