什么是注解?
![]()
内置注解
![]()
package com.wjx.annotation;
//什么是注解
public class Test01 extends Object {
/**
* @Override 重写
* @return
*/
@Override
public String toString() {
return super.toString();
}
/**
* @Deprecated 不推荐程序员使用,但是可以使用
*/
@Deprecated
public void test(){
}
}
元注解
![]()
package com.wjx.annotation;
import java.lang.annotation.*;
//测试元注解
@MyAnnotation
public class Test02 {
public void test(){
}
}
//自定义注解
//Target 表示我们的直接可以用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})
//@Retention 表示我们的注解在什么地方运行有效
//runtime>class>source
@Retention(value = RetentionPolicy.RUNTIME)
//@Documented 表示我们是否将注解生成在javadoc中
@Documented
//@Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}
自定义注解
![]()
package com.wjx.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注解
* @author dell
*/
public class Test03 {
//注解可以显示赋值,如果没有默认值,我们就必须给注解赋值
@MyAnnotation2(schools = {"清华"})
public void test(){}
}
/**
* @author dell
*/
@Target(value = {ElementType.TYPE,ElementType.METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
//注解的参数:参数类型 + 参数名()
String name() default "";
int age() default 0;
//如果默认值为-1,代表不存在
int id() default -1;
String[] schools();
}