java1.5新特性中的注解:相当于一个标记,javac编译器,开发工具和其他程序可以用反射来
了解是否有某种标记,从而做相应的操作。
@SuppressWarnings:警告
@Deprecated:过时
@Override:重写
元注解:注解类上加持的注解称为元注解,一般是用来设置该注解类的运行时间以及作用范围。
了解是否有某种标记,从而做相应的操作。
@SuppressWarnings:警告
@Deprecated:过时
@Override:重写
元注解:注解类上加持的注解称为元注解,一般是用来设置该注解类的运行时间以及作用范围。
常见的有@Retention @Target
@Retention的属性值:枚举类RetentionPolicy的枚举常量(RetentionPolicy.RUNTIME RetentionPolicy.CLASS RetentionPolicy.SOURCE)
@Target的属性值:枚举类ElementType的枚举常量(TYPE,METHOD,CONSTRUCTOR,FIELD...)
自定义注解:
1.定义一个最简单的注解
2.把它加在某个类上
3.用反射进行测试类的定义上是否有注解
注解类的内部可以定义不同类型的变量,通过注解时设置不同的变量值,然后通过反射可以获取这些变量的值。
自定义注解:
1.定义一个最简单的注解
2.把它加在某个类上
3.用反射进行测试类的定义上是否有注解
@Retention(RetentionPolicy.RUNTIME)//元注解
@Target({ElementType.METHOD,ElementType.TYPE})
@interface MyAnnotation
{}
@MyAnnotation
class AnnotationTest
{
public static void main(String[] args)
{
if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class))
{
MyAnnotation annotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);
System.out.println(annotation);
}
}
}
注解类的内部可以定义不同类型的变量,通过注解时设置不同的变量值,然后通过反射可以获取这些变量的值。
注解可以定义的变量类型有:8个基本数据类型 数组 String Enum Class Annotation
一个简答的反射取得注解变量值的例子:
注解类MetaAnnotation:
public @interface MetaAnnotation {
String value() default "zhangsan";
}
注解类MyAnnotation
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,ElementType.METHOD})
public @interface MyAnnotation {
String value() default "abc" ;
String color() default "red";
int[] arrInt() ;
TrafficLamp lamp() default TrafficLamp.RED;
Class clazz() default String.class;
MetaAnnotation metaAnnotation() default @MetaAnnotation("lisi");
}
注解测试类AnnotationTest:
import java.lang.reflect.Method;
@MyAnnotation(color="blue",arrInt=1,clazz=Integer.class,metaAnnotation=@MetaAnnotation("wangwu"))
public class AnnotationTest {
@MyAnnotation(value="xyz",arrInt=2,lamp=TrafficLamp.YELLOW)
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){
MyAnnotation annotation = AnnotationTest.class.getAnnotation(MyAnnotation.class);
System.out.println(annotation);
}
Method method = AnnotationTest.class.getMethod("main", String[].class);
if(method.isAnnotationPresent(MyAnnotation.class)){
MyAnnotation methodAnnotation =method.getAnnotation(MyAnnotation.class);
System.out.println(methodAnnotation);
}
}
}