1.java5.0在java.lang包中定义了3种标准的annotation类型:
A.Override:
java.lang.Override是一个marker annotation类型,它被用作标注方法。它说明了被标注的方法重载了父类的方法,起到了断言的作用。如果我们使用了这种annotation在一个没有覆盖父类方法的方法时,java编译器将以一个编译错误来警示。
B.Deprecated:
同样Deprecated也是一个marker annotation。当一个类型或者类型成员使用@Deprecated修饰的话,编译器将不鼓励使用这个被标注的程序元素。
C.SuppressWarnings:
@SuppressWarnings被用于有选择的关闭编译器对类、方法、成员变量、变量初始化的警告。在java5.0,sun提供的javac编译器为我们提供了-Xlint选项来使编译器对合法的程序代码提出警告,此种警告从某种程度上代表了程序错误。例如当我们使用一个generic collection类而又没有提供它的类型时,编译器将提示出"unchecked warning"的警告。
2.新建一个注解
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyTag { //与接口类似,只是多了一个@
public enum FontColor {RED, GREEN, BLUE}; //声明一个枚举值
String name();
String value() default "[aaaa]"; //设置其默认值
FontColor fontColor() default FontColor.BLUE;
String [] strs() default "[null]";
}
注意:
1./* @ Retention,表明注释信息将可以在运行时刻通过反射机制得到。如果不加入这个标签,上面的代码将没有任何输出。*/
2./*Target表示此类型的annotation 只能用于修饰方法声明。*/
3.如果只有一个属性时,可以只用写 value()方法,然后在方法前声明注解时不用写MyTag(value="aa"),而直接写成MyTag("adddd")
3.使用
public class TempTest {
@Test
@MyTag(name="aa",value="ccc",fontColor=MyTag.FontColor.RED,strs={"1","2","3"} )
public void test1(){
List<String> list1=new ArrayList<String> ();
list1.add("aaa");
List<String> list2=new ArrayList<String> ();
list2.add("aab");
Collections.addAll(list1, new String [] {"1"});
assertEquals("1",list1.get(1));
getAnnotion();
}
private void getAnnotion(){
try {
// Method method=this.getClass().getMethod("test1");
// method.getAnnotation(MyTag.class);
Annotation[] annotation =this.getClass().getMethod("test1").getAnnotations();//取得注解所在方法,从而得到所有注解
for (Annotation tag :annotation) {
if(MyTag.class.isAssignableFrom(tag.annotationType())){ //只输出是MyTag注解的内容
System.out.println("Tag is:" + tag);
System.out.println("tag.name()" + ((MyTag) tag).name());
System.out.println("tag.age()" + ((MyTag) tag).value());
for(String str: ((MyTag)tag).strs()){
System.out.println(str);
}
}
}
} catch(NoSuchMethodException e) {
e.printStackTrace();
}
}
}