Java注解

参考https://blog.csdn.net/briblue/article/details/73824058


注解的理解

Java注解,可以简单理解为一个标签,用来标示某个对象。

注解的定义

public @interface TestAnotation

它的声明与接口类似,只是在interface前加上@修饰

注解的属性

id,name,age 只能用java的基本数据类型int,String等

注解的元注解

@Retention

保留期,主要是

RetentionPolicy.RUNTIME 运行中

RetentionPolicy.SOURCE 源代码中

RetentionPolicy.Class 编译期

@Target

指明注解运用的地方

@Documented

关联javadoc

@Repeatable

可重复的

@inherited

继承

注解的应用

注解可以用在类,方法,属性上

@TestAnotation(id = 3, name = "xl")
public class Test {
	
	@Field
	private String value;
	
	@Check
	public void get(){
		
	}
}

比如一个简单的注解

@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Target(value = { ElementType.TYPE })
public @interface TestAnotation {
	
	int id();
	
	String name();
	
	int age() default 18;

}
public static void main(String[] args) {
	boolean t = Test.class.isAnnotationPresent(TestAnotation.class);
	
	System.out.println(t);
	
	if(t){
		TestAnotation tmp = Test.class.getAnnotation(TestAnotation.class);
		System.out.println(tmp.age());
		System.out.println(tmp.id());
		System.out.println(tmp.name());
		
		Annotation[] a = Test.class.getAnnotations();
		for(Annotation annotation : a){
			System.out.println("==="+annotation.annotationType().getSimpleName());
		}
	}
}

Java预置的注解

@Override

@Deprecated

@SuppressWarnings

注解的提取

采用反射提取类,属性,方法值

@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD })
public @interface Fly {

	String val() default "f";

}
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD })
public @interface Check {
	
	String value() default "x";
	
}
@TestAnotation(id = 3, name = "xl")
public class Test {
	
	@Fly(val="xxx")
	public String value;
	
	@Check
	public void get(){
		
	}
}
	public static void main(String[] args) throws 
           NoSuchFieldException, SecurityException, NoSuchMethodException {		
		
		Field value = Test.class.getDeclaredField("value");
		value.setAccessible(true);
		
		Fly c = value.getAnnotation(Fly.class);
		if(c != null){
			System.out.println(c.val());
		}
		
		Method get = Test.class.getDeclaredMethod("get");

        if ( get != null ) {
            // 获取方法中的注解
            Annotation[] ans = get.getAnnotations();
            for( int i = 0;i < ans.length;i++) {
                System.out.println("method testMethod             
                     annotation:"+ans[i].annotationType().getSimpleName());
            }
        }
		
	}

运行结果:

xxx
method testMethod annotation:Check

要想获取到运行的结果,注解中的@Retention(RetentionPolicy.RUNTIME)必不可少。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值