注解,如何声明一个注解,自己做一个像@test的注解

声明一个注解 @interface 注解名{}

声明注解中的成员(注解的属性类型可以有哪些?)
1.基本类型
2.String
3.枚举类型
4.注解类型
5.Class类型
6.以上类型的一维数组类型

代码:
test注解原理

MyAnnotation.java

package day20200822;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;


@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    
    
	
	String name() default "fanjia";
	int id() default 1;
	Class clazz() default Object.class;

}

Demo02.java

package day20200822;

public class Demo02 {
    
    
	@MyAnnotation(name="fan")
	public void test1(){
    
    
		System.out.println("test1");
		
	}
	
	@MyAnnotation(id=2)
	public void test2(){
    
    
		System.out.println("test2");
	}
	
	
	
	public void test3(){
    
    
		System.out.println("test3");
		
	}
	
	

}

Demo03.java

/**
 * 
 */
package day20200822;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author fanjia
 *
 */
public class Demo03 {
    
    
	public static void main(String[] args) throws Exception {
    
    
		Class clz =Demo02.class;
		Method[] methods = clz.getMethods();
		for(Method method : methods){
    
    
			MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
			//System.out.println(annotation.name());
			//System.out.println(annotation.getClass().getName());
			if(method.getName().startsWith("test") && annotation != null){
    
    
				System.out.println("方法名"+method.getName());
				System.out.println("注解:name()"+annotation.name());
				System.out.println("注解:id()" + annotation.id());
				System.out.println("注解:clazz()" + annotation.clazz());
				
				method.invoke(clz.newInstance());
				
				System.out.println();
			}
			
			
		}
		
		
		
		
		
		
	}

}

猜你喜欢

转载自blog.csdn.net/qq_43472248/article/details/108173916