黑马程序员---<<基础加强---1.5新特性(中)(注解(Annotation))>>(二)

2014-11-24 08:59:05 · 作者: · 浏览: 2
nnotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.*;
//定义此注解保留在字节码中
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() ;
String Color()default "red";//设置默认值是"red"
}
@MyAnnotation("java")
public class ApplyMyAnnotation {
public static void main(String[] args) {
/**
* 这是获得类上的注解,也可以获得方法上的注解,下面就以获得类上的注解为例
*/
if (ApplyMyAnnotation.class.isAnnotationPresent(MyAnnotation.class)) {// 判断此类上是否存在指定的注解类
MyAnnotation annotation = (MyAnnotation) ApplyMyAnnotation.class
.getAnnotation(MyAnnotation.class);
System.out.println("value="+annotation.value());
System.out.println("Color="+annotation.Color());
}
}
}
结果:
value=java
Color=red
从调用的程序中,也可以看出,只有一个属性可以需要赋值的话,可以省略属性名。否则@注解类(属性名=值)
3.2.综合类型
[java]
/*枚举类*/
public enum Week{
SUN,MON;
}
/**
* 注解类
*/
public @interface annotationText {
String value();
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.*;
//定义此注解保留在字节码中
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() ;
String Color()default "red";//设置默认值是"red"
Week week() default Week.MON;//枚举类型
int [] array() default {1,2,3};//数组类型
annotationText annotation() default @annotationText("MY");//注解类型
Class classDemo() default Integer.class;//Class类型
}
@MyAnnotation(value="java",Color="green",week=Week.SUN,array=5,annotation=@annotationText("YOU"),classDemo=String.class)//数组array={4,5,6}
public class ApplyMyAnnotation {
public static void main(String[] args) {
/**
* 这是获得类上的注解,也可以获得方法上的注解,下面就以获得类上的注解为例
*/
if (ApplyMyAnnotation.class.isAnnotationPresent(MyAnnotation.class)) {// 判断此类上是否存在指定的注解类
MyAnnotation annotation= (MyAnnotation) ApplyMyAnnotation.class
.getAnnotation(MyAnnotation.class);
System.out.println("value="+annotation.value());
System.out.println("Color="+annotation.Color());
System.out.println("week="+annotation.week());
System.out.println("array长度="+annotation.array().length);
System.out.println("注解类型值="+annotation.annotation().value());
System.out.println("Class类型值="+annotation.classDemo());
}
}
}
结果:
value=java
Color=green
week=SUN
array长度=1
注解类型值=YOU
Class类型值=classjava.lang.String
4.Method上的注解
[java]
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* 注解类
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface annotationText {
String value();
}
public class ApplyMyAnnotation {
public static void main(String[] args) throws Exception {
Method methodshow = ApplyMyAnnotation.class.getMethod("show");
annotationText anno = methodshow.getAnnotation(annotation