目录
概念
通过反射获取类、函数、或成员上运行时注解信息,从而实现动态控制程序运行的逻辑;
实例
如下面的这个Java工程:
源码如下:
Base.java
package my;
public interface Base {
public String strValue();
public int intValue();
}
Description.java
package my;
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;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Description {
String DesStrValue();
int DesIntValue() default 10086;
}
ParseAnn.java
package my;
import java.lang.reflect.Method;
public class ParseAnn {
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
// 1.使用类加载器加载类
try {
Class c = Class.forName("my.SubClass");
//找到类的注解
boolean isExist = c.isAnnotationPresent(Description.class);
if(isExist) {
//拿到注解实例
Description d = (Description)c.getAnnotation(Description.class);
System.out.println(d.DesStrValue() + "\t" + d.DesIntValue());
//找到注解上的方法
Method[] ms = c.getMethods();
for(Method m : ms) {
boolean isMExist = m.isAnnotationPresent(Description.class);
if(isMExist) {
Description dm = (Description)m.getAnnotation(Description.class);
System.out.println(dm.DesStrValue() + "\t" + dm.DesIntValue());
}
}
}
}
catch(ClassNotFoundException e) {
System.out.println(e.toString());
}
SubClass subClass = new SubClass();
subClass.strValue();
}
}
SubClass.java
package my;
@Description(DesStrValue = "这是一个类")
public class SubClass implements Base {
@Override
@Description(DesStrValue = "SubClass 中的StrValue的")
public String strValue() {
// TODO Auto-generated method stub
System.out.println();
return null;
}
@Override
@Description(DesStrValue = "SUbClass中intValue的", DesIntValue = 10010)
public int intValue() {
// TODO Auto-generated method stub
return 0;
}
}
程序运行截图如下:
这里拿到函数上注解的方式有两种,一个是使用:
Annotation[] as = m.getAnnotations();
一种是使用Description)m.getAnnotation(Description.class);
如上面的代码所示!