zoukankan      html  css  js  c++  java
  • 【通过配置文件来反射运行类中的方法】

    package com.yjf.esupplier.common.test;
    
    import java.io.FileReader;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Method;
    import java.util.Properties;
    
    /**
     * @author shusheng
     * @description 通过配置文件来反射运行类中的方法
     * @Email shusheng@yiji.com
     * @date 2019/1/5 18:37
     */
    public class ReflectDemo4 {
    
        public static void main(String[] args) throws Exception {
            // 反射前的做法
            Person p = new Person();
            p.show();
            // 反射后的做法
            Properties prop = new Properties();
            FileReader fr = new FileReader("test.txt");
            prop.load(fr);
            fr.close();
            // 获取数据
            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);
        }
    
    }
    package com.yjf.esupplier.common.test;
    
    /**
     * @author shusheng
     * @description
     * @Email shusheng@yiji.com
     * @date 2018/12/29 13:42
     */
    public class Person {
    
            private String name;
            int age;
            public String address;
    
            public Person() {
            }
    
            private Person(String name) {
                this.name = name;
            }
    
            Person(String name, int age) {
                this.name = name;
                this.age = age;
            }
    
            public Person(String name, int age, String address) {
                this.name = name;
                this.age = age;
                this.address = address;
            }
    
            public void show() {
                System.out.println("show方法的输出");
            }
    
            public void method(String s) {
                System.out.println("method方法的输出: " + s);
            }
    
            public String getString(String s, int i) {
                return s + "---" + i;
            }
    
            private void function() {
                System.out.println("function方法的输出");
            }
    
            @Override
            public String toString() {
                return "Person [name=" + name + ", age=" + age + ", address="
                        + address
                        + "]";
            }
    
    }
    终身学习者
  • 相关阅读:
    01背包
    manacher马拉车算法
    盒子放球的DP
    Children’s Queue
    抽象类_作为接口
    斯特林数
    欧拉路HDU3018
    2019 SDN上机第三次作业
    第05组 Alpha冲刺(2/4)
    Alpha冲刺(1/4)
  • 原文地址:https://www.cnblogs.com/zuixinxian/p/11275256.html
Copyright © 2011-2022 走看看