这个问题是一个跟进一个问题,我以前
java: get all variable names in a class获取注释从类变量
找到我要的是从一个类中获取变量,但不是让他们的一切,我只是想具有注释@isSearchable
的变量。
所以基本上我有2个问题:
如何创建一个注释?
如何仅通过此批注过滤我的字段?
还有一件事,如果它是我经常使用的东西是可取的(我猜测反射应该是慢的)。
谢谢
这个问题是一个跟进一个问题,我以前
java: get all variable names in a class获取注释从类变量
找到我要的是从一个类中获取变量,但不是让他们的一切,我只是想具有注释@isSearchable
的变量。
所以基本上我有2个问题:
如何创建一个注释?
如何仅通过此批注过滤我的字段?
还有一件事,如果它是我经常使用的东西是可取的(我猜测反射应该是慢的)。
谢谢
/** Annotation declaration */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface isSearchable{
//...
}
@isSearchable
public String anyField = "any value";
检查,如:
//use MyClass.class.getDeclaredFields() if you want the fields only for this class.
//.getFields() returns the fields for all the class hierarchy
for(Field field : MyClass.class.getFields()){
isSearchable s = field.getAnnotation(isSearchable.class);
if (s != null) {
//field has the annotation isSearchable
} else {
//field has not the annotation
}
}
还有一个问题,是否可以使用它来节省一些代码写作时间? –
它取决于,通常我们应该避免反思,因为它涉及到开销,但是如果在可维护性/可读性/可测试性方面获得很多,我认为我们可以使用它。并且如果需要的话,应该依靠剖析器来了解该区域以进行优化 –
Field.getDeclaredAnnotations()给你每个字段的注解。
要回答你的补充问题,我通常会期望反射速度很慢。话虽如此,我可能不会担心优化,直到这成为你的问题。
提示:确保你在检查up-to-date Javadoc。谷歌倾向于给我Java 1.4 Javadocs,并且注释在Java 5之前不存在。
如何仅通过此注释过滤我的字段?
您可以通过这个简单的代码片段
Field field = ... //obtain field object
Annotation[] annotations = field.getDeclaredAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof IsSearchable){
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
}
在上面得到片断你基本上只过滤IsSearchable
注释。
关于你one more thing
查询
是反射将是缓慢的讨论here,如果能够避免,会建议你避免。
下面是一个例子
class Test {
@IsSearchable
String str1;
String str2;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface IsSearchable {
}
public static void main(String[] args) throws Exception {
for (Field f : Test.class.getDeclaredFields()) {
if (f.getAnnotation(IsSearchable.class) != null) {
System.out.println(f);
}
}
}
}
打印
java.lang.String Test.str1
@TJCrowder我不熟悉的注释,或者如果这是一个用例。 谢谢大家的回答,这真的很有帮助 –