注解在spring框架中经常使用。
java从1.5开始支持注解。
注解的理解:
注解是什么?
从JDK5开始,Java增加对元数据的支持,也就是注解,注解与注释是有一定区别的,可以把注解理解为代码里的特殊标记,这些标记可以在编译,类加载,运行时被读取,并执行相应的处理。通过注解开发人员可以在不改变原有代码和逻辑的情况下在源代码中嵌入补充信息。
注解怎么用?
@XXXXX
定义类,方法时,加上@XXX
@MyFirstAnnotation(value = "test")
public void test() throws NoSuchMethodException {
//方法上面的注解获取
MyFirstAnnotation annotation = this.getClass().getMethod("test").getAnnotation(MyFirstAnnotation.class);
// 注解对象的使用
System.out.println("method="+annotation.method());
System.out.println("value="+annotation.value());
}
自己怎么写一个注解?
/**
* 自定义一个注解
* @Documented 定义该注解是否出现在javadoc中,可选
* @Target(ElementType.TYPE) 指定Annotation的类型属性,指定其修饰的是类,接口,或者方法,可选,不指定,则所有地方都能使用
* @Retention(RetentionPolicy.RUNTIME) 指定annotation的策略属性,可选运行时或者类加载
* @interface 定义注解,意味实现了Annotation接口
*
*/
底层实现是动态代理。
package com.wang.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
public class AnnotationTest {
public static void main(String[] args) throws NoSuchMethodException {
AnnotationTest annotationTest = new AnnotationTest();
annotationTest.test();
}
/**
* 注解的使用
* test方法具有注解MyFirstAnnotation
* @throws NoSuchMethodException
*/
@MyFirstAnnotation(value = "test")
public void test() throws NoSuchMethodException {
//方法上面的注解获取
MyFirstAnnotation annotation = this.getClass().getMethod("test").getAnnotation(MyFirstAnnotation.class);
// 注解对象的使用
System.out.println("method="+annotation.method());
System.out.println("value="+annotation.value());
}
}
/**
* 自定义一个注解
* @Documented 定义该注解是否出现在javadoc中,可选
* @Target(ElementType.TYPE) 指定Annotation的类型属性,指定其修饰的是类,接口,或者方法,可选,不指定,则所有地方都能使用
* @Retention(RetentionPolicy.RUNTIME) 指定annotation的策略属性,可选
* @interface 定义注解,意味实现了Annotation接口
*
*/
@Documented
//@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface MyFirstAnnotation {
String value() default "";
String method() default "POST";
}