Java注解总结

注解说明

注解其实是代码里的特殊标记,这些标记可以在编译、类加载、运行时被读取,并执行相应的处理。

通过使用注解,可以在class源文件嵌入一些补充信息。

基本注解

  • 限定充血父类方法:@Override
  • 限定某个程序类、方法已过时:@Deprecated
  • 抑制编译器警告:@SuppressWarnings
  • “堆污染”警告:@SafeVarargs
  • 函数式接口:@FunctionalInterface

元注解

  • 设置注解保留时间:@Retention
  • 设置注解修饰的程序单元:@Target
  • 该注解会生成文档:@Documented
  • 设置继承性:@Inherited

定义注解

使用@interface关键字

public @interface Test{
    
}

使用该注解

@Test
public class MyClass{
    
    @Test
    public void info(){
        
    }
}

注解设置成员变量,注解中的成员变量都是以方法的形式定义

public @interface MyTag{
    String name() default "hello";
    int age() default 18;
}

使用注解指定变量

public class Test{
    @MyTag(name="张三",age=26)
    public void info(){
        
    }
}

获取注解信息

通过反射获取该类上注解的信息

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyTag {
	
	// 注解中的成员变量必须以方法的形式定义
	String name() default "name";
	int age() default 18;
}
@Test
public class MyClass {
	
	@Test
	public void info() {
		
	}
	
	@MyTag(name="a",age=12)
	public void test() {
		
	}
}
	public static void main(String[] args) throws NoSuchMethodException, SecurityException, ClassNotFoundException {
		Annotation[] annotations = Class.forName("com.chen.MyClass").getMethod("test").getAnnotations();
		for (Annotation annotation : annotations) {
			System.out.println(annotation);
		}
	}

输出:@com.chen.MyTag(name=a, age=12)

获取详细的信息

	public static void main(String[] args) throws NoSuchMethodException, SecurityException, ClassNotFoundException {
		Annotation[] annotations = Class.forName("com.chen.MyClass").getMethod("test").getAnnotations();
		for (Annotation annotation : annotations) {
			if (annotation instanceof MyTag) {
				System.out.println("name:"+((MyTag)annotation).name());
				System.out.println("age:"+((MyTag)annotation).age());
			}
		}
	}

输出:

name:a
age:12
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值