javaEE 注解, 自定义注解


MyAnno.java(定义注解):

package com.xxx.annotation;

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

@Target({ElementType.METHOD,ElementType.TYPE})  // 表示该注解可以用以标注方法和类
@Retention(RetentionPolicy.RUNTIME)   // 表示该注解是运行时级别(运行时可见) (只有运行时级别,才能通过反射获取到)
public @interface MyAnno {  // 用@interface定义注解

	//注解的属性 (后面要有小括号)
	String name();
	
	int age() default 28;  // 可以为属性指定默认值
	
	//String value();
	//String[] value();
	
}
Test.java(使用定义的注解):
package com.xxx.annotation;
@MyAnno(name = "zhangsan")
public class Test {
	
	@SuppressWarnings("all")
	@MyAnno(name = "zhangsan")  // 注解必须指定其属性的值。属性有默认值的可以不用指定
	//@MyAnno({ "aaa","bbb","ccc"})  如果注解的属性只有一个value属性,可以省略"value="只写属性的值。
	public void show(String str){
		System.out.println("show running...");
	}
	
}
MyAnnoParser.java(注解解析,通过反射获取使用的注解):
package com.xxx.annotation;

import java.lang.reflect.Method;
 
public class MyAnnoParser {
 
	public static void main(String[] args) throws NoSuchMethodException, SecurityException {
 
		//获得字节码对象
		Class clazz = MyAnnoTest.class;
		
		//获得所有的方法
		Method[] methods = clazz.getMethods();
		if(methods!=null){
			//获得使用了@MyAnno注解的方法
			for(Method method:methods){
				//判断该方法是否使用了@MyAnno注解
				boolean annotationPresent = method.isAnnotationPresent(MyAnno.class);
				if(annotationPresent){  //如果该方法使用了MyAnno注解
					method.invoke(clazz.newInstance(), null);
				}
			}
		}
		
		Method method = clazz.getMethod("show", String.class);
		//获得show方法上的@MyAnno注解
		MyAnno annotation = method.getAnnotation(MyAnno.class); // 只有运行时级别的注解,才能通过反射获取到
		//获得@MyAnno上的属性值
		System.out.println(annotation.name()); //zhangsan
		System.out.println(annotation.age());  //28
		
		// .....
	}
}



猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/80952494