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 + "]"; } }