Simple reflection frame

Java class implementing a simple reflection:

  • You can not change any code in the class. You can create objects of any class, any method can be performed
    by changing the configuration file only way to achieve a different method of class
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * 框架类
 */
public class ReflectTest {
    public static void main(String[] args) throws  Exception{
        // 可以创建任意类的对象,可以指向任意方法
        /*
           前提: 不能改变该类的任何代码。可以创建任意类的对象,可以执行任意方法
         */
        /*Person p = new Person();
        p.eat();*/

        /*Student s = new Student();
        s.sleep();*/

        // 1.加载配置文件
        // 1.1创建Properties
        Properties pro = new Properties();
        // 1.2加载配置文件,转换为一个集合
        // 1.2.1获取class目录下的配置文件的方法
        ClassLoader classLoader = ReflectTest.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("pro.properties");
        pro.load(is);

        // 2.获取配置文件中的数据
        String className = pro.getProperty("className");
        String methodName = pro.getProperty("methodName");

        // 3.加载该类进内存
        Class cls = Class.forName(className);
        // 4. 创建对象
        Object obj = cls.newInstance();
        // 5.获取方法对象
        Method method = cls.getMethod(methodName);
        // 6.执行方法
        method.invoke(obj);
    }
}

Profiles
Snipaste_2019-07-23_10-09-39.jpg

Guess you like

Origin www.cnblogs.com/minghaiJ/p/11230129.html