Java 用注释的方式代替配置文件
一个注释接口
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Pro {
String className();
String methodName();
}
/*
上面的代码就像:
public class ProImpl implements Pro{
public String ClassName(){
return "Reflect.Tow.Demo1";
}
public String MethodName(){
return "show";
}
}
*/
一个类:
public class Demo01 {
public void show(){
System.out.println("Demo1....show...");
}
}
Main:
@Pro(className = "Reflect.Tow.Demo01",methodName = "show")
public class ReflectTest {
public static void main(String[] args) throws Exception {
//可以创建任意类的对象,可以执行任意方法
//前提不能改变该类的任何代码,可以创建任意的类对象,可以执行任意方法
//1.解析注解
//1.1获取该类字节码的文件对象
Class<ReflectTest> reflectTestClass = ReflectTest.class;
//2获取注释对象
Pro annotation = reflectTestClass.getAnnotation(Pro.class);//其实结束在内存中去生成一个该注解接口的子类实现对象
String className = annotation.className();//那这个方法的返回值就是Reflect.Tow.Demo1咯
String methodName = annotation.methodName();
System.out.println(className);
System.out.println(methodName);
Class aClass = Class.forName(className);
Object o = aClass.newInstance();
Method method = aClass.getMethod(methodName);
method.invoke(o);
}
}
结果: