一贵少、 Annotation的工作方式
Annotation并不會(huì)直接影響程序的語(yǔ)義,它的工作方式類似于程序的類庫(kù)或者工具堆缘,它反過來會(huì)對(duì)程序的語(yǔ)義有所影響滔灶。Annotation可以從源文件、class文件或者以運(yùn)行時(shí)反射的多種方式被讀取吼肥。
二录平、 幾個(gè)常用的注解
1、Override注解表示子類要重寫父類對(duì)應(yīng)的方法缀皱。
2斗这、Deprecated注解表示方法不建議被使用;
3啤斗、SurpressWarnings注解表示一直警告涝影。
4 、Retentoion注解用于在定義主解時(shí)修飾注解該如何讀取争占。在使用時(shí)必須搭配屬性value燃逻,value的取值是一個(gè)RetentionPolicy枚舉類型:
@Retention(RetentionPolicy.RUNTIME) //表示在運(yùn)行時(shí)反射獲取Annotation
//@Retention(RetentionPolicy.CLASS) //表示從class文件獲取Annotation
//@Retention(RetentionPolicy.SOURCE) //表示從源文件獲取Annotation
5 、Target注解用于在定義主解時(shí)限定注解的使用位置臂痕。在使用時(shí)也必須搭配屬性value伯襟,value的去值是一個(gè)ElementType枚舉類型:
//不同的枚舉類型表示該注解只能作用的位置
@Target(value = ElementType.METHOD)
//@Target(value = ElementType.ANNOTATION_TYPE)
//@Target(value = ElementType.CONSTRUCTOR)
//@Target(value = ElementType.FIELD)
//@Target(value = ElementType.LOCAL_VARIABLE)
//@Target(value = ElementType.PACKAGE)
//@Target(value = ElementType.PARAMETER)
//@Target(value = ElementType.TYPE)
//@Target(value = ElementType.TYPE_PARAMETER)
//@Target(value = ElementType.TYPE_USE)
三、 自定義注解
1握童、自定義注解時(shí)姆怪,當(dāng)注解的屬性名時(shí)value時(shí),對(duì)其賦值時(shí)可以不指定屬性名稱直接寫上屬性值即可;除了value之外其他的屬性都必須以name = value的方式賦值稽揭。
2俺附、Demo
(1) 自定義的注解
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME) //表示在運(yùn)行時(shí)反射獲取Annotation
//@Retention(RetentionPolicy.CLASS) //表示從class文件獲取Annotation
//@Retention(RetentionPolicy.SOURCE) //表示從源文件獲取Annotation
public @interface MyAnnotation
{
String hello() default "hello";
String world();
}
(2)注解的使用
public class MyTest
{
@MyAnnotation(hello = "tiangjin", world = "shanghai")
@Deprecated
@SuppressWarnings("unchecked")
public void output()
{
System.out.println("output something!");
}
}
(2)利用反射查看注解
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class MyReflectTest
{
public static void main(String[] args) throws Exception
{
MyTest myTest = new MyTest();
Class<?> c =myTest.getClass();
Method method = c.getMethod("output", new Class[] {});
if (method.isAnnotationPresent(MyAnnotation.class))
{
method.invoke(myTest, new Object[] {});
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
String hello = myAnnotation.hello();
String world = myAnnotation.world();
System.out.println(hello + " " + world);
}
Annotation[] annotations = method.getAnnotations();
for(Annotation annotation : annotations)
System.out.println(annotation.annotationType().getName());
}
}
四、 注解的繼承關(guān)系
默認(rèn)情況下溪掀,子類是不會(huì)繼承父類中的Annotation的事镣,如果想要繼承父類中的某些Annotation,需要在在定義該Annotation形態(tài)時(shí)加上java.lang.Annoatation.Inherited形態(tài)的Annotation揪胃。