反射 Class Method Field 初步使用
程序员文章站
2024-01-25 19:48:52
...
[size=large]代码小例子:[/size]
package com.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectTest
{
// object's copy
public static Object copy(Object obj) throws Exception, Exception
{
Class<? extends Object> clazz = obj.getClass();
// Constructor con = clazz.getConstructor(new
// Class[]{int.class,String.class});
Constructor con = clazz.getConstructor();
// Object o = con.newInstance(new Object[]{1,"2"});
Object o = con.newInstance(new Object[] {});
Field[] field = clazz.getDeclaredFields();
for (Field field2 : field)
{
String name = field2.getName();
String firstLetter = name.substring(0, 1).toUpperCase();
String getMethodName = "get" + firstLetter + name.substring(1);
String setMethodName = "set" + firstLetter + name.substring(1);
Method getMethod = clazz.getMethod(getMethodName, new Class[] {});
Method setMethod = clazz.getMethod(setMethodName,
new Class[] { field2.getType() });
Object value = getMethod.invoke(obj, new Object[] {});
setMethod.invoke(o, new Object[] { value });
// System.out.println(field2);
System.out.println(getMethodName);
System.out.println(setMethodName);
}
// System.out.println(o);
return o;
}
public static void main(String[] args) throws Exception
{
People p = new People();
p.setAge(1);
p.setName("liu");
p.setHight("66kg");
People p2 = (People) ReflectTest.copy(p);
System.out.println(p2.getAge());
System.out.println(p2.getHight());
System.out.println(p2.getName());
}
}
class People
{
private int age;
private String name;
private String hight;
public People()
{
}
public People(int age, String name)
{
this.age = age;
this.name = name;
}
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 String getHight()
{
return hight;
}
public void setHight(String hight)
{
this.hight = hight;
}
}
上一篇: java反射的应用 构造方法 成员变量