Java盲区
注解
-
注解一般配合反射使用,通过反射获取注解的属性的值
-
自定义注解:
public @interface MyAnno{ String value(); String dValeu() default "666"; }
- 在注解内部只有书信和,没有方法,即value() —> 表示为属性,而不是方法
- 通过添加default关键词,来为注解的属性赋值
- 如果没有dafult的关键词,则需要在声明注解时进行赋值
- 若注解内部没有任何属性,则该注解为声明的作用,即标志
-
元注解:
-
对其他注解进行修饰的注解
-
Retention:指定注解的声明周期
public enum RetentionPolicy { /** * Annotations are to be discarded by the compiler. */ SOURCE, //被编译器丢弃 /** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. */ CLASS, //编译时加载进去,即加载到class文件中去,但是不会加载到内存中 /** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. * * @see java.lang.reflect.AnnotatedElement */ RUNTIME //会被加载到内存中,可以通过反射读取 } - Source / Class 默认 - 只有声明为Runntime的注解才会被加载到JVM中
-
Target:用于指定被修饰的Annotation可以修饰哪些程序元素(Class,…)
public enum ElementType { /** Class, interface (including annotation type), or enum declaration */ TYPE, /** Field declaration (includes enum constants) */ FIELD, /** Method declaration */ METHOD, /** Formal parameter declaration */ PARAMETER, /** Constructor declaration */ CONSTRUCTOR, /** Local variable declaration */ LOCAL_VARIABLE, /** Annotation type declaration */ ANNOTATION_TYPE, /** Package declaration */ PACKAGE, /** * Type parameter declaration * * @since 1.8 */ TYPE_PARAMETER, /** * Use of a type * * @since 1.8 */ TYPE_USE, /** * Module declaration. * * @since 9 */ MODULE }
-
Documented:用于指定被改类修饰的注解在javadoc工具提取出成文档,默认情况下,javadoc是不包含注解的
- 定义Docunmented注解,必须将Rentention设置为Runntime
-
Inherited:被他修饰的Annotation将具有继承性,如果某个类使用了改注解,则其子类将自动用于该注解
-
-
-
通过反射获得注解信息
Class clazz = MyAnno.class; Annotation []anns = clazz.getAnnotations(); for(Annotation a : anns ) System.out.println(a); // 只能获得runtime的注解
-
JDK 8.0新特性
-
可重复注解;
- 在需要重复注解的位置添加注解Repeatable注解,设置成员值为第三方的注解
- 设置需要重复注解的Retention,Inherited和Target的值于第三方的值相同
- 设置成功即可重复注解
-
类型注解:
-
在Target中添加Type_Paramerte的参数,使得可以添加到泛型中
class Generic<@MyAnno(name = "55") T>{ }
-
在Target中添加Type_Use注解,使得所有为类型的位置都可以添加注解
class Generic<@MyAnno(name = "55") T>{ ArrayList<@MyAnno(name = "33") String> list = new ArrayList(); }
-
-