反射
定义
JVM 在运行时 才动态加载的类或调用方法或属性,他不需要事先(写代码的时候或编译期)知道运行对象是谁。
demo
越过泛型检查
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19/**
* 练习: 一个ArrayList<Integer>集合,现在想在这个集合中添加一个字符串数据
*/
public class ReflectTest01 {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ArrayList<Integer> array =new ArrayList<>();
// array.add(10);
// array.add(20);
// array.add("str");
Class<? extends ArrayList> c = array.getClass();
Method m = c.getMethod("add", Object.class);
m.invoke(array,"hello");
m.invoke(array,"World");
System.out.println(array);
}
}
运行配置文件指定内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29/**
* 通过配置文件运行类中的方法
*/
public class ReflectTest02 {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
// Student s = new Student();
// s.study();
//加载数据
Properties prop = new Properties();
FileReader fr = new FileReader("myCharStream\\class.txt");
prop.load(fr);
fr.close();
/*
className=n04.student
methodName=study
*/
String className = prop.getProperty("className");
String methodName = prop.getProperty("methodName");
//通过反射来使用
Class<?> c = Class.forName(className);
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
Method m = c.getMethod(methodName);
m.invoke(obj);
}
}