Java 的反射机制
反射机制 是通过 外部的配置文件修改 避免了 内部代码的修改 ,降低了代码的耦合性, 提高了代码的可修改性
更多相关教程
class Service1{
public Service1(){}
public void method1(){
System.out.println("Service1 : method1");
}
}
public Service2{
public Service2(){}
public void method2(){
System.out.println("Service2 : method2")
}
}
传统方式
public class ServiceTest{
public static void main(String [] args){
new Service2().method2();
}
}
放射模式
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor
public class ServiceTest{
public static void main(String [] args) throws Exception{
File springconfigFile = new File("spring.txt");
Properties springConfig = new Properties();
springConfig.load(new FileInputStream(springconfigFile));
String className = springConfig.getProperty("class");
String methodName = springConfig.getProperty("method");
Class cs = Class.forName(className);
Method m = cs.getMethod(methodName);
Constructor cr = cs.getConstructor();
Object service = cr.newInstance();
m.invoke(service);
}
}
只需要修改文件即可,避免了内部代码的修改
spring.txt
class=Service1
method=method1