zoukankan      html  css  js  c++  java
  • 用反射实现简单的框架

    用反射实现一个简单的java类:

    • 不能改变该类的任何代码。可以创建任意类的对象,可以执行任意方法
      可以通过只改变配置文件的方式去实现不同的类中的方法
    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);
        }
    }
    

    配置文件
    Snipaste_2019-07-23_10-09-39.jpg

  • 相关阅读:
    csp-2020-s游记
    线性DP
    tarjan无向图
    tarjan有向图
    树前置知识普及
    hash
    可持久化线段树&主席树
    [HAOI 2015] 树上染色
    [Contest on 2020.11.24] Beetle
    [Contest on 2020.11.24] Candy
  • 原文地址:https://www.cnblogs.com/minghaiJ/p/11230129.html
Copyright © 2011-2022 走看看