- 自定义注解
import java.lang.annotation.*;
@Target({ElementType.FIELD,ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface pro {
String className() ;
String methodName() ;
}
- 核心代码(使用注解的方式实现配置类加载)
import annotation.pro;
import java.lang.reflect.Method;
@pro(className = "Entity.Student", methodName = "sleep")
public class ReflectCase2 {
public static void main(String[] args) throws Exception {
Class<ReflectCase2> reflectCaseClass = ReflectCase2.class;
pro annotation = reflectCaseClass.getAnnotation(pro.class);
String className = annotation.className();
String methodName = annotation.methodName();
Class aClass = Class.forName(className);
Object obj = aClass.newInstance();
Method method = aClass.getMethod(methodName);
method.invoke(obj);
}
}