@开头
Override:重写
Deprecated:不建议被使用
SuppressWarnings:注解表示抑制警告 SuppressWarnings("unchecked")
Retention:一般用来修饰自定义注解 //RetentionPolicy有三个值 Class表示写入JVM但是不能读 RunTime表示写入JVM也能读 SOURCE表示不写如JVM
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注解
* */
@Retention(RetentionPolicy.RUNTIME)//RetentionPolicy有三个值 Class表示写入JVM但是不能读 RunTime表示写入JVM也能读 SOURCE表示不写如JVM
@Target(ElementType.METHOD) //用来指定该注解修饰对象 Method表示只能修饰方法 Type类、接口(包括注释类型)或枚举声明 等等 详情见Target
public @interface AnnotationTest {
String value() default "holle";
String value2();
}
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class Client {
public static void main(String[] args) throws Exception {
Client client=new Client();
Class<Client> classType=Client.class;//获取该类的class对象
Method method=classType.getDeclaredMethod("showSomething", new Class[]{});//根据class对象获取对应方法
if(method.isAnnotationPresent(AnnotationTest.class)){//如果该方法存在该类型注解返回true
method.invoke(client, new Object[]{});//反射调用方法
AnnotationTest t= method.getAnnotation(AnnotationTest.class);//获取该方法的所有该类型的注解
System.out.println(t.value());
System.out.println(t.value2());
}
Annotation[] list= method.getAnnotations();//获取该方法的所有注解
for(Annotation l : list){
System.out.println(l.annotationType().getName());
}
}
@Deprecated
@SuppressWarnings("unchecked")
@AnnotationTest(value="dawson",value2="mingbai")
public void showSomething(){
System.out.println("do something...");
}
}