查找某个类中是否有某个注解

代码概述:

有三个类

1、MyAnnotation2--注释

2、UseMyAnnotation2--被测试的类

3、TestAnnotation2--进行测试的类


目的

利用类反射技术

遍历出某个类中所有有@MyAnnotation注解的变量和方法(由下面注解类决定放的位置)


代码demo:

MyAnnotation2类:--注释类

package cn.hncu.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)//记录在.class文件中,并且在运行时保留"注释"
@Target({ElementType.FIELD,ElementType.METHOD})//指定注解只能放在"变量"和"方法"上
public @interface MyAnnotation2 {
	public String value() default "默认值...";
}


UseMyAnnotation2类:--被测试的类:使用了@MyAnnotation注释

package cn.hncu.annotation;

public class UseMyAnnotation2 {
	@SuppressWarnings("unused")
	@MyAnnotation2
	private int num = 10;
	
	@SuppressWarnings("unused")
	private String str = "hncu";
	
	@MyAnnotation2("aaa...")
	public void a(){
	}
	
	public void b(){
	}
	
	@MyAnnotation2("ccc...")
	public void c(){
	}
}



TestAnnotation2:--测试类:查找UseMyAnnotation2类中有@MyAnnotation注解的变量和方法

package cn.hncu.annotation.test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.junit.Test;

import cn.hncu.annotation.MyAnnotation2;

/**
 * 思路:
 * 1、拿到Class对象
 * 2、拿到所有的变量数组Field[]
 * 3、遍历Field[],如果变量上有@MyAnnotation2注释,输出-变量名
 *   关键方法:★★f.isAnnotationPresent(MyAnnotation2.class)
 * 
 * 4、同理:拿到并遍历所有方法,找到输出-方法名
 */
public class TestAnnotation2{
	private static final String CLASS_NAME = "cn.hncu.annotation.UseMyAnnotation2";
	
	@Test
	public void test1() throws Exception{
		Class c = Class.forName(CLASS_NAME);
		
		//变量
		Field[] fs = c.getDeclaredFields();
		for(Field f:fs){
			if(f.isAnnotationPresent(MyAnnotation2.class)){
				System.out.println("有@MyAnnotation注释的变量:"+f.getName());
			}
		}
		
		//方法
		Method[] ms = c.getDeclaredMethods();
		for(Method m:ms){
			if(m.isAnnotationPresent(MyAnnotation2.class)){
				System.out.println("有@MyAnnotation注释的方法:"+m.getName());
			}
		}
	}
}


运行结果:

查找某个类中是否有某个注解_第1张图片

你可能感兴趣的:(Java)