Java SE Lesson 9(利用反射拷贝对象)
程序员文章站
2022-06-09 20:44:05
...
转自圣思园http://www.shengsiyuan.com
1. 要想使用反射,首先需要获得待处理类或对象所对应的Class对象。
2. 获取某个类或某个对象所对应的Class对象的常用的3种方式:
a) 使用Class类的静态方法forName:Class.forName(“java.lang.String”);
b) 使用类的.class语法:String.class;
c) 使用对象的getClass()方法:String s = “aa”; Class<?> clazz = s.getClass();
3. 若想通过类的不带参数的构造方法来生成对象,我们有两种方式:
a) 先获得Class对象,然后通过该Class对象的newInstance()方法直接生成即可:
Class<?> classType = String.class;
Object obj = classType.newInstance();
b) 先获得Class对象,然后通过该对象获得对应的Constructor对象,再通过该Constructor对象的newInstance()方法生成:
Class<?> classType = Customer.class;
Constructor cons = classType.getConstructor(new Class[]{});
Object obj = cons.newInstance(new Object[]{});
4. 若想通过类的带参数的构造方法生成对象,只能使用下面这一种方式:
Class<?> classType = Customer.class;
Constructor cons = classType.getConstructor(new Class[]{String.class, int.class});
Object obj = cons.newInstance(new Object[]{“hello”, 3});
5. Integer.TYPE返回的是int,而Integer.class返回的是Integer类所对应的Class对象。
package com.test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionTester
{
/**
* 通过反射拷贝对象
* @throws IllegalAccessException
* @throws InstantiationException
*/
public Object copy(Object object) throws Exception
{
Class<?> classType = object.getClass();
// Constructor cons = classType.getConstructor(new Class[]{});
// Object obj = cons.newInstance(new Object[]{});
//
// //以上两行代码等价于下面一行代码
// Object obj2 = classType.newInstance();
Object objectCopy = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
//获取对象的所有成员变量
Field[] fields = classType.getDeclaredFields();
for(Field field : fields )
{
String name = field.getName();//获得成员变量的名称
String firstLetter = name.substring(0,1).toUpperCase();//将属性的首字母变为大写
String getMethodName = "get" + firstLetter + name.substring(1);
String setMethodeName = "set" + firstLetter + name.substring(1);
Method getMethod = classType.getMethod(getMethodName, new Class[]{});
Method setMethod = classType.getMethod(setMethodeName, new Class[]{field.getType()});
Object value = getMethod.invoke(object, new Object[]{});
setMethod.invoke(objectCopy, new Object[]{value});
}
return objectCopy;
}
public static void main(String[] args) throws Exception
{
People p = new People("java",10);
p.setId(1L);
ReflectionTester test = new ReflectionTester();
People people = (People)test.copy(p);
System.out.println(people.getId()+","+people.getName()+","+people.getAge());
}
}
class People
{
private Long id;
private String name;
private int age;
public People()
{
}
public People(String name, int age)
{
this.name = name;
this.age = age;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
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;
}
}
上一篇: 【Java SE】反射 Reflect
下一篇: Java SE Lesson 7