Java注解

来源:互联网 发布:java发短信验证码 编辑:程序博客网 时间:2024/06/03 19:11
java注解
注解也叫做元数据,是一种代码级别的说明。注解可以用在
包、类、属性、方法、参数等上面,对源代码的一种标记。

作用:
1.根据注解可以生成文档
2.根据代码中注解的标识可以用反射机制对代码数据的访问
3.通过代码中注解的表示可以让编译器实现对代码的基础检查

实现
声明一个注解通过@interface即可,public @interface custom{}

定义好注解之后需要定义该注解的作用域和生命周期
作用域:该注解应该用在什么地方,如用在方法、属性、包上等
生命周期:该注解保持在什么阶段,如源代码中、编译器中、运行时
三种保持策略
1.SOURCE 保持在源代码中,编译的时候编译器将其忽略
2.CLASS  编译的时候被编译到class文件中,但jvm运行的时候会将其忽略

3.RUMTIME 编译的时候被编译到class文件中,jvm运行的时候还将其保留,因此可以利用反射机制进行获取

代码:
定义一个注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.FIELD})
public @interface Custom {


}

@Document 可以生成Java文档
@Target   表示注解的作用域
@Retention 注解的保持策略

可以在注解里定义参数及默认值
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
public @interface Custom {

String name() default "张三";


}
参数相当于声明一个方法,该方法只能声明为public,可以省略

例子:

package core.java.annoation;import java.lang.annotation.Annotation;import java.lang.reflect.Field;import java.lang.reflect.Method;public class AnnoationTest {public static void main(String[] args) {Class<?> cls = User.class;try {Field field = cls.getDeclaredField("name");Annotation[] annotations = field.getAnnotations();for(Annotation annotation : annotations){String annoationName = annotation.annotationType().getSimpleName();System.out.println("注解名称:" + annoationName);Class<?> cl = annotation.annotationType();System.out.println("注解类型为:" + cl);Custom custom = (Custom)annotation;System.out.println("注解的属性值:" + custom.name());//获取注解上的方法Method[] methods = cl.getMethods();for(Method method : methods){//获取方法名String name = method.getName();//获取方法返回值类型Class<?> type = method.getReturnType();//获取默认返回值Object object = method.getDefaultValue();System.out.println("注解的方法名:" + name + ",返回值类型:" + type + ",默认返回值:" + object);}}} catch (Exception e) {e.printStackTrace();} }}package core.java.annoation;public class User {@Custom(name = "李四")private String name;}package core.java.annoation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Documented@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})public @interface Custom {String name() default "张三";}


0 0
原创粉丝点击