@Override
public void run() {// 重写父类的run()方法// ...
}@Deprecated
public class OldClass {// ...
}@SuppressWarnings("unchecked")
public List<SomeClass> getSomeList() {// ...
}@Retention(RetentionPolicy.RUNTIME) // 指定注解保留到运行时
@Target(ElementType.METHOD) // 指定注解适用于方法
public @interface MyAnnotation {String value();int count() default 1;
}public class MyClass {@MyAnnotation(value = "example", count = 5)public void myMethod() {// ...}
}MyClass obj = new MyClass();
Method method = obj.getClass().getMethod("myMethod");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
String value = annotation.value(); // 获取注解的元素值
int count = annotation.count();package com.lidaochen.test;public class CJavaTest {public void eat(){System.out.println("我喜欢吃西瓜!");}
}
package com.lidaochen.test;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Pro {String className();String methodName();
}
package com.lidaochen.test;import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.util.Properties;@Pro(className = "com.lidaochen.test.CJavaTest", methodName = "eat")
public class CJavaDemo {public static void main(String[] args) throws Exception{// 1、获取该类的字节码对象Class cls = CJavaDemo.class;// 2、获取上边的注解对象Pro an = (Pro) cls.getAnnotation(Pro.class);// 3、调用注解对象中定义的抽象方法,获取返回值String className = an.className();String methodName = an.methodName();System.out.println(className);System.out.println(methodName);// 4、加载该类进内存Class mJavaTest = Class.forName(className);// 创建对象Object obj = mJavaTest.newInstance();// 获取方法对象Method method = mJavaTest.getMethod(methodName);// 执行方法method.invoke(obj);}
}