java自定义注解实现
Posted yzqs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
}
}
以上是关于java自定义注解实现的主要内容,如果未能解决你的问题,请参考以下文章