Service1.java

package reflection;
 
public class Service1 {
 
    public void doService1(){
        System.out.println("业务方法1");
    }
}

Service2.java

package reflection;
 
public class Service2 {
 
    public void doService2(){
        System.out.println("业务方法1");
    }
}

spring.txt(D:\spring)

class=reflection.Service1
method=doService1

Test.java

package reflection;
 
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Properties;
 
public class Test {
 
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) throws Exception {
 
        //从spring.txt中获取类名称和方法名称
        File springConfigFile = new File("d:\\spring.txt");
        Properties springConfig= new Properties();
        springConfig.load(new FileInputStream(springConfigFile));
        String className = (String) springConfig.get("class");
        String methodName = (String) springConfig.get("method");
         
        //根据类名称创建类对象
        Class clazz = Class.forName(className);
        //根据方面名称,获取方法
        Method m = clazz.getMethod(methodName);
        //获取构造器
        Constructor c = clazz.getConstructor();
        //根据构造器,实例化出对象
        Object service = c.newInstance();
        //调用对象的指定方法
        m.invoke(service);
         
    }
}

 

相关文章:

  • 2022-12-23
  • 2021-04-05
  • 2022-12-23
  • 2022-02-27
  • 2021-08-18
  • 2022-12-23
  • 2021-10-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-03-07
  • 2021-11-22
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案