1.注解及其作用
我们小伙伴在初学java的时候,最开始应该都学习过注释,通俗的说,注释就是给人看的,与运行代码无关。而注解是给机器看的,代码可以进行调用,影响代码的执行。在我们学习一些java框架的时候,会发现有很多注解,学习完注解,会对它底层,源码有进一步的了解。
2.内置注解
-
@Override
这个注解大家应该不陌生,在项目中应该会经常遇到,它的作用是重写父类的方法。当子类继承父类需要重写父类的方法的时候,就必须使用这个注解了。如果这个方法不是父类的方法,就不能使用这个注解了,使用就报错。反之如果是父类的方法重写,就必须要用此注解了。
-
@deprecated
这个注解是程序员人为添加的一种标识性注解,添加这个注解的方法被默认是不好的,不推荐使用的方法。当然只是一种主观上的态度,对程序运行没有丝毫的影响。但是调用此方法的时候会有一行横线穿过被调用的方法。
-
@SuppressWarnings(“all”)
这个注释是镇压警告的意思,在我们编程的过程中,会经常碰到一些警告,例如你编写的变量没有使用,引入了多余的包,idea都会有提示,用了这个注释之后就没有提示了。当然建议大家可以不需要使用它,有一些提示反而更好,能帮助我们找到问题,况且这些警告在代码中也不是很明显,不会影响大家的视觉体验
3.元注解
元注解其实就是定义注解的注解,会使用它之后,我们就可以自定义自己的注解了,首先我们需要了解一些东西。
-
@Target(用来说明注解可以用在哪些地方,后面加参数)
源码如下 例如写成@Target(value = {ElementType.METHOD,ElementType.CONSTRUCTOR})
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Target { /** * Returns an array of the kinds of elements an annotation type * can be applied to. * @return an array of the kinds of elements an annotation type * can be applied to */ ElementType[] value(); }
/** 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 *******用户类型
-
@Retention(用来说明注解的存在周期)
源码如下,例如参数写成@Retention(value = RetentionPolicy.RUNTIME)
作用周期RUNTIME>CLASS>SOURCE
运行时>编译后>源码
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Retention { /** * Returns the retention policy. * @return the retention policy */ RetentionPolicy value(); }
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, /** * 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 }
-
@Document(将该注解被包含在javadoc的java文档中)
这个没有参数,可以直接只用。
-
@Inherited(表明了子类可以继承父类的注解)
也没有参数,直接使用
4.自定义注解
例如创建的这个wtk注解,
- 注解的默认构创建方法是@interface 方法名().然后就是注解的属性要加上(),
- 然后可以在属性上面加上默认值,例如 String a() default “1”;不写的话就是默认值。
- 然后如果只有1个参数时,可以使用value创建,如使用String value();在使用的时候就直接省去了(value=“1”),是直接写参数值1.
public class text{
@Target(value = {ElementType.METHOD,ElementType.CONSTRUCTOR})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@interface wtk {
String a();
}
@wtk(a = "66")
public static void main(String[] args) {
}
}