java 反射初步

来源:互联网 发布:pcb绘图软件中文版 编辑:程序博客网 时间:2024/05/24 07:16

需要操作的对象:


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());}}


原创粉丝点击