自定义注解 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 { // 1.获取字节码文件 Class<ReflectCase2> reflectCaseClass = ReflectCase2.class; // 2.获取注解 pro annotation = reflectCaseClass.getAnnotation(pro.class); //3.加载注解 String className = annotation.className(); String methodName = annotation.methodName(); // 4.创建对象和方法 Class aClass = Class.forName(className); Object obj = aClass.newInstance(); Method method = aClass.getMethod(methodName); method.invoke(obj); } }