一、通過反射動態加載 類名和方法
1、配置文件
classname=reflect.Student (包名.類名)
methodname=sayHi (方法名)
1、首先,屬性文件加載配置文件。
2、獲得加載配置文件後的值
3、獲取反射對象
4、反射出方法對象
5、反射調用方法
public static void demo04() throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, FileNotFoundException, IOException {
//屬性文件
Properties prop = new Properties();
prop.load(new FileReader("class.txt"));
String classname = prop.getProperty("classname");
String methodname= prop.getProperty("methodname");
Class<?> perClazz = null;
//Class入口
try {
perClazz= Class.forName(classname);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Method method = perClazz.getMethod(methodname);
method.invoke(perClazz.newInstance());
}
二、反射可以越過泛型檢查
如代碼中註釋掉的部分,List集合是Integer類型的,因此不能加入String類型,但是在反射裏,是可以越過泛型檢查的。
public static void demo05() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
ArrayList<Integer> list = new ArrayList<>();
list.add(123);
list.add(12);
list.add(1);
//list.add("zs");
Class<?> class1 = list.getClass();
Method method = class1.getMethod("add", Object.class);//object任何類型參數
// method.invoke(class1.newInstance(), "zs");//方法調用時反射創建對象實例
method.invoke(list, "zs");//上面對象是new出來的,和list是兩個不同的對象
System.out.println(list);
}
三、給任何類的任意對像的任何屬性賦值
因爲調用 set 的方法需要 對象.set屬性(value) 這樣的格式,參數列表中所缺的正是屬性,因此通過反射獲得。
//yyy.setxxx(value)
public static void setProperty(Object obj, String propertyName, Object value) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Class<?> class1 = obj.getClass();//獲取反射
Field field = class1.getDeclaredField(propertyName);//獲取屬性
field.setAccessible(true);
field.set(obj, value);//obj對象的field屬性賦值爲value
}
方法調用如下:
public static void demo06() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Person per = new Person();
PropertyUtil.setProperty(per, "name", "zs");
PropertyUtil.setProperty(per, "age", 23);
Student stu = new Student();
PropertyUtil.setProperty(stu, "score", 9);
System.out.println(per.getName()+","+per.getAge());
System.out.println(stu.getScore());
}
Tips:
雖然可以通過反射訪問private等訪問修飾符;但實際開發不建議這樣使用,因此可能會影響程序混亂