1 package com.yubaby.reflect;
2
3 import com.yubaby.domain.Person;
4
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.lang.reflect.InvocationTargetException;
8 import java.lang.reflect.Method;
9 import java.util.Properties;
10
11 /*
12 * 案例:
13 * 需求:写一个"框架",不能改变该类的任何代码的前提下,可以帮我们创建任意类的对象,并且执行其中任意方法
14 * 实现:
15 1. 配置文件
16 2. 反射
17 * 步骤:
18 1. 将需要创建的对象的全类名和需要执行的方法定义在配置文件中
19 2. 在程序中加载读取配置文件
20 3. 使用反射技术来加载类文件进内存
21 4. 创建对象
22 5. 执行方法
23 */
24
25 /**
26 * 框架类
27 * 需求:可以创建任意类的对象,可以执行任意方法
28 * 前提/要求:不能改变该类的任何代码
29 * 比如下方:person和student需要手动创建/更改对象
30 * 即搞一个针对不同类不同对象万能的,不用手动更改的
31 * 通过配置文件操作的优点:使程序扩展能力更强
32 */
33 public class ReflectTest {
34 public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
35 /*Person person = new Person();
36 person.eat();
37 Student student = new Student();
38 student.sleep();*/
39
40 //1. 将需要创建的对象的全类名和需要执行的方法定义在配置文件中
41 //自定义配置文件pro.properties(名称、后缀随便,无硬性要求;创建在src下)
42
43 //2 在程序中加载读取配置文件
44 //2.1 创建Properties类对象properties
45 Properties properties = new Properties();
46 //2.2 获取本类所需的配置文件
47 ClassLoader classLoader = ReflectTest.class.getClassLoader();
48 InputStream is = classLoader.getResourceAsStream("pro.properties");
49 //2.3 加载配置文件
50 properties.load(is);
51
52 //3 使用反射技术来加载类文件进内存
53 //3.1 获取配置文件中事先定义的数据
54 String className = properties.getProperty("className");
55 String methodName = properties.getProperty("methodName");
56 //3.2 加载该类进内存
57 Class<?> cls = Class.forName(className);
58
59 //4. 创建对象
60 //4.1 类对象
61 /*Object obj = cls.newInstance();
62 //https://blog.csdn.net/qq_44312950/article/details/108782753
63 //java1.9版本后class.newInstance()方法被弃用*/
64 Object obj = cls.getDeclaredConstructor().newInstance();
65 //4.2 方法对象
66 Method declaredMethod = cls.getDeclaredMethod(methodName);
67
68 //5. 执行方法
69 declaredMethod.invoke(obj);
70
71 /*
72 className=com.yubaby.domain.Person
73 methodName=eat
74
75 eat...
76 */
77
78 /*
79 className=com.yubaby.reflect.Student
80 methodName=sleep
81
82 sleep...
83 */
84 }
85 }
1 package com.yubaby.domain;
2
3 public class Person {
4 private String name;
5 private int age;
6
7 public int a;
8 protected int b;
9 int c;
10 private int d;
11
12 public Person() {
13 }
14
15 public Person(String name, int age) {
16 this.name = name;
17 this.age = age;
18 }
19
20 public void setName(String name) {
21 this.name = name;
22 }
23
24 public void setAge(int age) {
25 this.age = age;
26 }
27
28 public String getName() {
29 return name;
30 }
31
32 public int getAge() {
33 return age;
34 }
35
36 @Override
37 public String toString() {
38 return "Person{" +
39 "name='" + name + '\'' +
40 ", age=" + age +
41 ", a=" + a +
42 ", b=" + b +
43 ", c=" + c +
44 ", d=" + d +
45 '}';
46 }
47
48 public void eat(){
49 System.out.println("eat...");
50 }
51
52 public void eat(String food){ //函数重载
53 System.out.println("eat:" + food);
54 }
55 }