栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

重复注解与类型注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

重复注解与类型注解

创建注解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;



public class TestAnnotation {
	//1.8还没有NonNull注解   需要配合框架checker framework    不允许为空,会在编译时报错
	private  Object obj = null;
	@Test
	public void test() throws NoSuchMethodException, SecurityException {
		Class 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) {
		
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/325297.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号