黑马程序员
注解–注释注解
- 测试类
- pro注解解析
- 测试主方法
package A_Part02.annotation02;
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();
}
package A_Part02.annotation02;
public class Demo1 {
public void show(){
System.out.println("demo1...show...");
}
}
package A_Part02.annotation02;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@Pro(className = "A_Part02.annotation02.Demo1",methodName = "show")
public class ReflectTest {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException, ClassNotFoundException {
Class<ReflectTest> reflectTestClass = ReflectTest.class;
Pro annotation = reflectTestClass.getAnnotation(Pro.class);
String className = annotation.className();
String methodName = annotation.methodName();
Class aClass = Class.forName(className);
Object o = aClass.newInstance();
Method method = aClass.getMethod(methodName);
method.invoke(o);
}
}