package com.ygl.reflect;标签:反射,name,printStackTrace,age,Object,Method,Field,catch,public From: https://blog.51cto.com/u_10028442/5824126
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectTest {
public Object copy(Object object) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{
//使用对象的getClass()方法,前提先有对象实例
Class<?> clazz=object.getClass();
System.out.println(clazz.getName());//com.ygl.reflect.Customer
try {
/*
//无参的构造器
Constructor cons=clazz.getConstructor(new Class[]{});
//无参的实例
Object obj=cons.newInstance(new Object[]{});
System.out.println(obj);
//上面两个方法等价于
Object obj2=clazz.newInstance();//只能构造无参的对象
*/
Constructor cons=clazz.getConstructor(new Class[]{String.class,int.class});
Object obj=cons.newInstance(new Object[]{"ygl",25});
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return object;
}
public static void main(String[] args) {
ReflectTest reflectTest=new ReflectTest();
try {
reflectTest.copy(new Customer());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println();
}
}
class Customer{
private Long id;
private String name;
private int age;
public Customer() {
}
public Customer(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;
}
}