Java注解的理解及使用

元注解:表示用于注解的注解

  • @Documented:用于表示是否期望javadoc命令生成的文档中体现注解的内容
  • @Retention:表示注解的生命周期,存活时间
  • @Target:表示被修饰的注解可用于哪些地方,如变量、类、方法上
  • @Inherited:表示是否期望子类能继承

(1)@Retention详细说明

可选参数如下:

  • RetentionPolicy.SOURCE : 在编译阶段丢弃。@Override, @SuppressWarnings都属于这类注解,不影响项目代码的运行;
  • RetentionPolicy.CLASS : 在类加载的时候丢弃,是所有注解的默认值;
  • RetentionPolicy.RUNTIME : 始终不会丢弃,通常用于自定义注解。
    使用格式:@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)

(2)@Retention详细说明

  • @Target(java.lang.annotation.ElementType.FIELD):表示被修饰的注解只能用在类的成员变量上;
  • @Target(java.lang.annotation.ElementType.LOCAL_VARIABLE):表示被修饰的注解只能用在局部变量上;
  • @Target(java.lang.annotation.ElementType…METHOD):表示被修饰的注解只能用在成员方法上;
  • @Target(java.lang.annotation.ElementType.PARAMETER):表示被修饰的注解只能用在方法的参数上;
  • @Target(java.lang.annotation.ElementType.TYPE):表示被修饰的注解只能用在类、接口或enum;

内置注解

  • @Deprecated:表示所标注的内容,不再被建议使用,开发工具中使用效果如下;@Deprecated
  • @Override:用于方法上,表示该方法是重写父类的方法;
    @Override
  • @SuppressWarnings:是在方法上使用,用于抑制警告,注意下图中第9行和第14行的行号侧边的标志区别;
     @SuppressWarnings
  • @SafeVarargs:用于抑制参数类型安全检查警告;
@SafeVarargs
public static <T> void testSafeVarargs(T ... types){

}
  • @FunctionalInterface:主要用于编译级错误检查,加上该注解,当你写的接口不符合函数式接口定义的时候,编译器就会报错。
@FunctionalInterface
interface testFunctionalInterface{
     void test();
}

自定义注解

  • 注解格式:@interface 注解名 {}
  • 注解参数支持数据类型:所有基本数据类型,String类型,枚举enum类型,Class类型,Annotation类型。
  • 默认值default:使用如String name() default “Tom”,表示name不指定值时,采用默认值Tom
    案例代码:
import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@interface Custom{
	String name() default "Tom";
	int age() default 22;
}


public class CustomTest {
	
	public static void main(String[] args) throws ClassNotFoundException {
		Class<CustomTest> thisClass=CustomTest.class;
		Method[] methods=thisClass.getDeclaredMethods();
		for(Method method:methods) {
			if(method.isAnnotationPresent(Custom.class)) {
				Custom custom=method.getAnnotation(Custom.class);
				String name=custom.name();
				int age=custom.age();
				System.out.println("名字:"+name+",年龄:"+age);
			}
		}
	}
	
	@Custom
	void testCustom1() {}
	
	@Custom(name="Jerry")
	void testCustom2() {}
	
	@Custom(name="Jerry",age=20)
	void testCustom3() {}

}

运行结果:
运行结果

发布了5 篇原创文章 · 获赞 8 · 访问量 1310

猜你喜欢

转载自blog.csdn.net/pwn2017211808/article/details/104450014
今日推荐