【读书笔记】 《Thinking in java》注解

xiaoxiao2026-08-02  12

A.注解:也被称为元数据,为我们在代码中添加信息提供了一种形式化的方法。 注解是众多引入到Java SE5中的重要语言变化之一。提供了完整地描述程序所需的信息。 B.Java中有三种标准注解:@Override  @Deprecated  @SuppressWarnings 四个元注解:

    @Target: 用来定义你的注解将应用于什么地方(方法?域?)      @Retention:用来定义注解在哪一个级别可用(源代码中SOURCE、类文件CLASS、或者运行时RUNTIME)      @Documented:将此注解包含在javadoc中      @Inherited:允许子类继承父类中的注解 C.定义一个注解

@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) Public @interface Test{}

     @Test定义很像一个借口,其中@Target和@ Retention 叫元注解      @Target:用来定义你的注解将应用于什么地方(方法?域?)      @Retention:用来定义注解在哪一个级别可用(源代码中SOURCE、类文件CLASS、或者运行时RUNTIME) D.定义另两种种形式的注解

   @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) Public @interface UseCase{ Public int id(); Public String description() default “no description” }

注解中的元素不能有不确定的值,也就是说,元素必须要么有默认值,要么在使用注解的时候提供元素的值。

@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Constraints { boolean primaryKey() default false; boolean allowNull() default true; boolean unique() default false; } @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface SQLInteger { String name() default ""; Constraints constraints() default @Constraints; }

E.注解处理器  使用反射机制查找注解标志来处理注解,如果没有注解处理器,那注解也没有比注释更有用。

   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); } }

F.注解元素的类型 所有的基本类型(8种); String; Class Enum Annotation 以上类型的数组 G.基于注解的单元测试@Unit 前置@Test 表明该方法是单元测试方法。@Test将验证并确保这些方法没有参数,并且返回值是boolean 或者void。使用@Uint测试,可以自己随意命名函数的名字。 对于每一个单元测试,@Unit都会用默认的构造器创建出一个对象,并在该对象上运行测试,然后丢弃该对象。如果类没有默认构造器,你可以使用@TestObjectCreate注解将该方法标记起来,然后@Unit会创建一个对象供使用。 注意,如果使用@TestObjectCreate为每个对象打开了资源,则在测试关闭的时候应该把这些资源关闭。 如果要向单元测试中添加一些额外的域,则可以使用@TestProperty注解。

 

转载请注明原文地址: https://www.6miu.com/read-5050596.html

最新回复(0)