0%
前言
学习框架底层必须要掌握反射。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Person { private String name; private int age; public Person(){ } public Person(String name, int age) { this.name = name; this.age = age; } }
|
获取类对象的三种方法
1 2 3 4 5 6 7
| @Test public void testClass() throws ClassNotFoundException { Class c1 = Person.class; Class c2 = new Person().getClass(); Class c3 = Class.forName("com.ahao.javaeeDemo.Person"); System.out.print(c1+"\n"+c2+"\n"+c3); }
|
通过反射创建对象
1 2 3 4 5 6 7 8 9 10
| @Test public void testNew() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { Class clazz = Class.forName("com.ahao.javaeeDemo.Person"); Person p1 = (Person) clazz.newInstance(); System.out.println("无参构造方法:"+p1.toString()); Person p2 = (Person) clazz.getConstructor(String.class, int.class).newInstance("张三", 12); System.out.println("有参构造方法:"+p2.toString()); }
|
操作Field
1 2 3 4 5 6 7 8 9 10 11 12
| @Test public void testField() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException { Class clazz = Class.forName("com.ahao.javaeeDemo.Person"); Person p1 = (Person) clazz.newInstance();
Field name = clazz.getDeclaredField("name"); name.setAccessible(true); name.set(p1, "张三"); System.out.println(p1.toString()); }
|
操作Method
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Test public void testMethod() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { Class clazz = Class.forName("com.ahao.javaeeDemo.Person"); Person p1 = (Person) clazz.newInstance();
Method method = clazz.getDeclaredMethod("setName", String.class); method.setAccessible(true); method.invoke(p1, "张三"); System.out.println(p1.toString()); }
|