Person p = new Person("cdj", 23); Class clazz1 = p.getClass();
Class clazz2 = Person.class; Class clazz = Class.forName("me.forz.javaReflect.path.Person");
获取Constructor
1 2 3 4
Constructor c1 = clazz.getConstructor(); // 无参构造器 Constructor c2 = clazz.getConstructor(String.class, int.class); // 有参 Person p = (Person) c2.newInstance("constru", 23);
获取Field
1 2 3 4 5
// 分两种, 是否是private // Field f = clazz.getField(fieldName); Field f = clazz.getDeclaredField(fieldName);// Field名称 f.setAccessible(true); //私有字段需要设置此项 f.set(obj, val);
ArrayList<Integer> al = new ArrayList<Integer>(); al.add(1); al.add(2); System.out.println(al); //[1, 2]
Class clazz = Class.forName("java.util.ArrayList"); Method m = clazz.getDeclaredMethod("add"大专栏 Java反射机制an>, Object.class); m.invoke(al, "a"); System.out.println(al); // [1, 2, a]
使用
动态代理
只能针对接口做代理; 需要实现InvocationHandler接口
假设有一个Fruit接口, 包含一个eat()方法, FruitImpl是一个实现
1 2 3 4 5 6 7 8 9 10
publicclass{ publicstaticvoidmain(String[] args){ FruitImpl fi = new FruitImpl(); fi.eat();// 输出: eating
MyInvocationHandler mih = new MyInvocationHandler(fi); Fruit f = (Fruit) Proxy.newProxyInstance(fi.getClass().getClassLoader(), fi.getClass().getInterfaces(), mih); f.eat(); // 输出 beforn eatingn after } }