重复注解与类型注解

创建注解MyAnnotion

@Repeatable(MyAnnotations.class)注解可以重复

package 新特性;

import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Repeatable(MyAnnotations.class)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE,ElementType.TYPE_PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotion {
	
	String value() default "www";
}

MyAnnotations 注解容器

package 新特性;

import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Repeatable(MyAnnotations.class)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE,ElementType.TYPE_PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotion {
	
	String value() default "www";
}

重复注解的使用

package 新特性;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.junit.Test;

/**
 * 重复注解与类型注解
 * @author wangqiangac
 * @verion NCC-1.0
 * @since 2021-10-13 14:50:35
 */

public class TestAnnotation {
	//1.8还没有NonNull注解   需要配合框架checker framework    不允许为空,会在编译时报错
	private /* @NonNull */ Object obj = null;
	@Test
	public void test() throws NoSuchMethodException, SecurityException {
		Class<TestAnnotation> clazz = TestAnnotation.class;
		
		Method m1 = clazz.getMethod("show", new Class<?>[] {String.class});
		MyAnnotion[] annotations = m1.getAnnotationsByType(MyAnnotion.class);
		for (MyAnnotion myAnnotion : annotations) {
			System.out.println(myAnnotion.value());
		}
		
		Annotation[][] parameterAnnotations = m1.getParameterAnnotations();
		for (Annotation[] annotations2 : parameterAnnotations) {
			
			System.out.println(annotations2[0]);
			MyAnnotion myAnnotion = (MyAnnotion) annotations2[0];
			System.out.println(myAnnotion.value());
		}
	}
	@MyAnnotion("hello")
	@MyAnnotion("word")
	public void show(@MyAnnotion("abc") String str) {
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值