java获取注解
‘壹’ java反射机制 怎样获取到类上面的注解
//定义注解并指定java注解保留策略为运行时RUNTIME,运行时注入到JAVA字节码文件里
//这样才可以在运行时反射并获取它。
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@interfaceMyAnnotation{
Stringkey()default"";
intvalue()default0;
}
//使用注解
@MyAnnotation(key="key1",value=200)
classMyClass{}
//反射注解
publicstaticvoidmain(String[]args){
MyClassmyClass=newMyClass();
MyAnnotationannotation=myClass.getClass().getAnnotation(MyAnnotation.class);
System.out.println("key="+annotation.key()+" value="+annotation.value());
}
‘贰’ java获取当前类上的注解内容
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
@Target({ElementType.FIELD,ElementType.METHOD})//定义注解的作用目标**作用范围字段、枚举的常量/方法
@Documented//说明该注解将被包含在javadoc中
public @interface FieldMeta {
/**
* 是否为序列号
* @return
*/
boolean id() default false;
/**
* 字段名称
* @return
*/
String name() default "";
/**
* 是否可编辑
* @return
*/
boolean editable() default true;
/**
‘叁’ java 获取所有带注解的类
既然是基于spring,可以这样:
ResourcePatternResolver rpr = new ();
Resource[] res = rpr.getResources("classpath*: **/*.class"); // classpath*:带*号会找jar中的class
然后根据resource取clas路径就行
String className = res[0].getURL().getPath();
className = className.split("(classes/)|(!/)")[1];
className = className.replace("/", ".").replace(".class", "");
Object obj = Class.forName(className);
话说我最近也在写一个这样的MVC。。要不咱两合伙? 我写的也是基于注解,不过要支持REST风格
‘肆’ 如何java中程序如何得到@Id这样的注释
java注解类public @Interface Id{}
import该类然后在方法,其他类,或者变量前就可以使用@Id注解了