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
                        + "]";
            }
    
    }
    终身学习者
  • 相关阅读:
    一次linux启动故障记录
    linux 时间相关的一些总结
    linux 3.10 gro的理解和改进
    linux 3.10 的中断收包笔记
    一个有趣的nginx问题引发的小问题
    linux 3.10 tcp的accept测试
    linux mce的一些相关内容和用户态监控的设计方法
    C/C++(基础-运算符详解)
    C/C++(基础-常量,类型转换)
    C/C++(基础编码-补码详解)
  • 原文地址:https://www.cnblogs.com/zuixinxian/p/11275256.html
Copyright © 2011-2022 走看看