要想使用反射,首先需要获得待处理类或对象所对应的Class对象。
获取某个类或某个对象所对应的Class对象的常用的3种方式:
1. 使用Class类的静态方法forName,Class.forName(“java.lang.String”);
2. 使用类的.class语法:String.class;
3. 使用对象的getClass()方法:String s = “aa”; Class<?> clazz = s.getClass();
若想通过类的不带参数的构造方法来生成对象,有两种方式:
1.先获得Class对象,然后通过Class对象的newInstance()方法直接生成即可;
2.先获得Class对象,然后通过该对象获得对应的Constructor对象,再通过该Constructor对象的newInstance()方法生成;
public class ReflectTester { //该方法实现对象的拷贝操作 public Object copy(Object object) throws Exception{ Class classType = object.getClass(); //System.out.println(classType); //class my.reflect.Customer Object obj = classType.newInstance(); System.out.println(obj); //my.reflect.Customer@c17164 //以下两行代码等价于上面的classType.newInstance(); Constructor cons = classType.getConstructor(new Class[]{}); Object obj2 = cons.newInstance(new Object[]{}); System.out.println(obj2); //my.reflect.Customer@1fb8ee3 //通过带参数的构造方法生产对象 Constructor cons1 = classType.getConstructor(new Class[]{String.class, int.class}); Object obj3 = cons1.newInstance(new Object[]{"hello", 23}); System.out.println(obj3); //my.reflect.Customer@61de33 return null; } public static void main(String[] args) throws Exception{ ReflectTester test = new ReflectTester(); test.copy(new Customer()); }}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; }}