1. 要想使用反射,首先需要获得待处理类或对象所对应的 Class对象。
2. 获取某个类或某个对象所对应的 Class对象的常用的 3种方式: a) 使用Class类的静态方法 forName:Class.forName(“java.lang.String”);
String.class;
c) 使用对象的 getClass()方法:
String s = “aa”; Class clazz = s.getClass();
3. 若想通过类的不带参数的构造方法来生成对象,我们有两种方式: a) 先获得Class对象,然后通过该 Class对象的newInstance()方法直接生成即可:
Class classType = String.class;
Object obj = classType.newInstance();
Class classType = Customer.class; Constructor cons = classType.getConstructor(new Class[]{}); Object obj = cons.newInstance(new Object[]{});
Class classType = Customer.class; Constructor cons = classType.getConstructor(new Class[]{String.class, int.class}); Object obj = cons.newInstance(new Object[]{“hello”, 3});
public class ReflectTester { // 该方法实现对Customer对象的拷贝操作 public Object copy(Object object) throws Exception { //见上文3(b) Class classType = object.getClass(); 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 setMethodName = "set" + firstLetter + name.substring(1); Method getMethod = classType.getMethod(getMethodName, new Class[] {}); Method setMethod = classType.getMethod(setMethodName, new Class[] { field.getType() }); Object value = getMethod.invoke(object, new Object[] {}); //invoke()方法的第一个参数是指调用Method的对象,第二个参数是Method的参数 详见API setMethod.invoke(objectCopy, new Object[] { value }); } return objectCopy; } public static void main(String[] args) throws Exception { Customer customer = new Customer("Tom", 20); customer.setId(1L); //1L为Long型的1. ReflectTester test = new ReflectTester(); Customer customer2 = (Customer) test.copy(customer); System.out.println(customer2.getId() + "," + customer2.getName() + "," + customer2.getAge()); } } /* * Customer Bean */ 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; } }
通过对象得到类型
Class classType = object.getClass();
或者通过类名取得类型
Class classType = Class.forName("类名")
通过生成一个Method对象
Method setMethod = classType.getMethod(setMethodName(方法名),new Class[] { field.getType() } (参数));
然后调用 Object value = setMethod.invoke(object(谁调用这个方法), new Object[] {}(参数));
本文为<北京圣思园Java培训教学视频Java.SE 反射机制大总结>视频笔记