Java 注解

Java 注解,第1张

Java 注解

java注解-最通俗易懂的讲解

简介

注解:

  1. 一种特殊的类, 相当于“标签”,用于注释说明,可修饰类、接口、方法、参数等
分类 元注解

元注解是可以注解到注解上的注解,或者说元注解是一种基本注解,但是它能够应用到其它的注解上面。
可以这样理解:元注解也是一张标签,但是它是一张特殊的标签,它的作用和目的就是给其他普通的标签进行解释说明的。
元标签有 @Retention、@documented、@Target、@Inherited、@Repeatable 5 种。

定义

注解的属性也叫做成员变量。注解只有成员变量,没有方法。注解的成员变量在注解的定义中以“无形参的方法”形式来声明,其方法名定义了该成员变量的名字,其返回值定义了该成员变量的类型。

@documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Description {
    String text() default "";
}
使用

@Description可修饰类的成员变量

	
    @Description(text = "医院编码")
    @Column(name="hospital_code")
    private String hospitalCode;
注解内容的提取

在需要获取注解内容的时候,可通过反射提取。

成员变量注解
public static  List generateChangeContent(T source, U target) {
	List sourceFields = Arrays.asList(source.getClass().getDeclaredFields());
	for (Field sourceField : sourceFields) {
	   Description descAnno = sourceField.getAnnotation(Description.class);
	   Column columnAnno = sourceField.getAnnotation(Column.class);
	   if (descAnno == null || columnAnno == null) {
	       continue;
	   }
	   if (descAnno.text().contains("授权范围")) {
	   	//todo
	   }
	}
}
类注解
//首先可以通过 Class 对象的 isAnnotationPresent() 方法判断它是否应用了某个注解
public boolean isAnnotationPresent(Class annotationClass) {}

//获取 Annotation 对象。
public  A getAnnotation(Class annotationClass) {}
public Annotation[] getAnnotations() {}

@TestAnnotation()
public class Test {
    public static void main(String[] args) {
        boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class);
        if ( hasAnnotation ) {
            TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);
            System.out.println("id:"+testAnnotation.id());
            System.out.println("msg:"+testAnnotation.msg());
        }
    }
}





欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5684196.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存