美文网首页
注解annotation

注解annotation

作者: 英文名叫夏天 | 来源:发表于2018-12-19 14:02 被阅读0次

什么是注解

注解(Annotation) 提供了一种安全的类似注释的机制,为我们在代码中添加信息提供了一种形式化得方法,使我们可以在稍后某个时刻方便的使用这些数据(通过解析注解来使用这些 数据),用来将任何的信息或者元数据与程序元素(类、方法、成员变量等)进行关联。其实就是更加直观更加明了的说明,这些说明信息与程序业务逻辑没有关 系,并且是供指定的工具或框架使用的。Annotation像一种修饰符一样,应用于包、类型、构造方法、方法、成员变量、参数及本地变量的申明语句中。
Annotation其实是一种接口。通过java的反射机制相关的API来访问Annotation信息。相关类(框架或工具中的类)根据这些信息来决定如何使用该程序元素或改变它们的行为。Java语言解释器在工作时会忽略这些Annotation,因此在JVM中这些Annotation是“不起作用”的,只能通过配套的工具才能对这些Annotation类型的信息进行访问和处理。

Java SE5内置了三种标准注解

  • @Override,表示当前的方法定义将覆盖超类中的方法。
  • @Deprecated,使用了注解为它的元素编译器将发出警告,因为注解 @Deprecated是不赞成使用的代码,被弃用的代码。
  • @SuppressWarnings,关闭不当编译器警告信息。

Java提供了4中注解,专门负责新注解的创建

  • @Documented –注解是否将包含在JavaDoc中
  • @Retention –什么时候使用该注解
  • @Target –注解用于什么地方
  • @Inherited – 是否允许子类继承该注解


    image.png

定义注解的方式

注解的可用的类型包括以下几种:所有基本类型、String、Class、enum、Annotation、以上类型的数组形式。元素不能有不确定的值,即要么有默认值,要么在使用注解的时候提供元素的值。而且元素不能使用null作为默认值。注解在只有一个元素且该元素的名称是value的情况下,在使用注解的时候可以省略“value=”,直接写需要的值即可。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
     public String id();
     public String description() default "no description";
}

使用注解

public class PasswordUtils {
     @UseCase(id = 47, description = "Passwords must contain at least one numeric")
     public boolean validatePassword(String password) {
         return (password.matches("\\w*\\d\\w*"));
     }
 
     @UseCase(id = 48)
     public String encryptPassword(String password) {
         return new StringBuilder(password).reverse().toString();
     }
 }

注解处理器

public static void main(String[] args) {
     List<Integer> useCases = new ArrayList<Integer>();
     Collections.addAll(useCases, 47, 48, 49, 50);
     trackUseCases(useCases, PasswordUtils.class);
 }
 //方法注解 
 public static void trackUseCases(List<Integer> useCases, Class<?> cl) {
     for (Method m : cl.getDeclaredMethods()) {
         UseCase uc = m.getAnnotation(UseCase.class);
         if (uc != null) {
             System.out.println("Found Use Case:" + uc.id() + " "
                         + uc.description());
             useCases.remove(new Integer(uc.id()));
         }
     }
     for (int i : useCases) {
         System.out.println("Warning: Missing use case-" + i);
     }
 }
//字段注解
public static String getFiledComment(Object obj, String fieldName) {

        Field[] fields =obj.getClass().getDeclaredFields();
        String filedComment = "";
        for (Field field : fields) {
            if (fieldName.equals(field.getName())) {
                FieldComment fieldCommentAnnotation = field.getAnnotation(FieldComment.class);
                filedComment = fieldCommentAnnotation.desc();
                break;
            }

        }
        return filedComment;
    }

相关文章

网友评论

      本文标题:注解annotation

      本文链接:https://www.haomeiwen.com/subject/lwbdkqtx.html