java自定义注解实现

package annotition;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ClassInfo {
String name() default "";

}

++++++++++++++++++++++++++++++++++

package annotition;

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

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MethodInfo {
String value() default "";
}

++++++++++++++++++++++++++++++++++++++++++++++++

package annotition;
@ClassInfo(name = "hellow world")
public class MyAnnotition {
@MethodInfo("你好啊")
public void java(){}
}

+++++++++++++++++++++++++++++++++++++++++++++++

package annotition;

import static org.junit.Assert.*;

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

import junit.framework.Test;

public class AnnotationParse {
public static void parse() {
Class clazz = MyAnnotition.class;
//该类上存在ClassInfo注解
if (clazz.isAnnotationPresent(ClassInfo.class)) {
//从类上得到类的注解
ClassInfo classInfo = (ClassInfo) clazz.getAnnotation(ClassInfo.class);
//输出该注解的name属性
System.out.println(classInfo.name());


}
//获取该类的所有的方法
Method[] methods = clazz.getMethods();
for (Method method : methods) {
//如果该方法上存在MethodInfo注解
if (method.isAnnotationPresent(MethodInfo.class)) {
//获取上面的methodInfo注解
MethodInfo methodInfo = method.getAnnotation(MethodInfo.class);
//输出注解中的value属性
System.out.println(methodInfo.value());
}

}

}
@org.junit.Test
public void testName() throws Exception {
parse();
}
}

猜你喜欢

转载自www.cnblogs.com/yzqs/p/9177098.html