Java -- 反射示例
1. 反射: 即加载和解剖, 用于设计框架, 读取配置档 动态创建对象。
Person类,用于反射。
package com.kevin.class_test; public class Person { public String namestr="aaaa"; public Person() { System.out.println("public constructor"); } private Person(String name) { System.out.println("private constructor " + name); } public Person(String name1, String name2) { System.out.println("public constructor " + name1 + name2); } public void fun() { System.out.println("in fun: " + namestr); } public String fun(String name) { System.out.println("in fun: " + namestr + name); return "Yes"; } public static void main(String[] args) { System.out.println("in main"); for(String str : args) { System.out.println(str); } } }
反射的使用实例, 使用Junit测试
package com.kevin.class_test; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.junit.After; import org.junit.Before; import org.junit.Test; public class JunitTest { Class clazz = null; //建立Class对象 @Before public void before() throws Exception //初始化@before { System.out.println("before"); clazz = Class.forName("com.kevin.class_test.Person"); //加载类,一定要用类全名 } @Test public void test() throws Exception { Person person = (Person) clazz.newInstance(); //反射实例化对象 person.fun(); } @Test public void test2() throws Exception { Constructor cons = clazz.getDeclaredConstructor(String.class); //反射获取private方法 cons.setAccessible(true); //改变private属性 Person person = (Person) cons.newInstance("kevin"); //使用获取的构造器 实例化对象 person.fun(); } @Test public void test3() throws Exception { Person p = new Person(); Method method = clazz.getMethod("fun", String.class); //反射获取public方法 String result = (String) method.invoke(p, "xiang"); System.out.println("result: " + result); } @Test public void test4() throws Exception { Method method = clazz.getMethod("main", String[].class); //反射获取main方法 method.invoke(null, (Object)new String[]{"a","b"}); //必须将String[]掩饰为Object,不然会参数异常报错 } @Test public void test5() throws Exception { Person p = new Person(); Field field = clazz.getField("namestr"); //反射获取属性 Object value = field.get(p); //获取属性值 Class type = field.getType(); //获取属性值类型 if( type.equals(String.class) ) { String str = (String)value; //类型转换 System.out.println("str: " + str); } field.set(p, "bbbb"); //修改属性 System.out.println("str: " + p.namestr); } @After public void after() { System.out.println("atfer"); } }