您好我正在创建一个自定义Excel解析marshaller工具,您可以参考: How can I call getter/setter for property marked with custom annotation?
我现在需要的是能够找到所有注释,特别是如何找到嵌套对象或内部类的注释,然后调用该setter / getter。
例如:
public class MyOuterClass {
private InnerClass innerObject;
public void setInnerObject (InnerClass innerObject) {
this.innerObject = innerObject;
}
public InnerClass getInnerObject() {
return innerObject;
}
}
和
public class InnerClass {
// I need to get this field and call its setter from the class passed in, so something like:
// MyOuterClass outClass; outClass.getInnerObject.setFieldIWant("field")
// OR outClass.getInnerObject.getFieldIWant
// But have to be able to do at run time, having no knowledge of the class inside
// This must also work for a nested class
@ExcelColumn
private String fieldIWant;
public void setFieldIWant(String fieldIWant) {
this.fieldIWant = fieldIWant;
}
public String getFieldIWant() {
return fieldIWant;
}
}
答案 0 :(得分:4)
以下类实现AnnotatedElement
接口:
AccessibleObject
Class
Constructor
Field
Method
Package
在所述类的对象实例上,您可以调用:
<object>.isAnnotationPresent(Class<? extends Annotation> annotationClass)
指定要检查的注释的方法。
因此,在您的情况下,@ExcelColumn
的方法调用如下:
<object>.isAnnotationPresent(ExcelColumn.class)
然后你可以使用反射来迭代你想要检查的对象的字段/方法等,并在每个对象上调用.isAnnotationPresent
方法来检查它们是否具有所述注释。
因此,如果你想在字段(和嵌套字段)上做一些魔术,你可以创建一个这样的方法:
public void doMagicToFields(Object someObject){
// Get all declared fields.
Field[] fields = someObject.getClass().getDeclaredFields();
for(Field field: fields){
// If the field is annotated by @ExcelColumn
if(field.isAnnotationPresent(ExcelColumn.class){
// If the field is a String (add more checks as needed)
if(String.class.equals(field.getClass()){
// Set the fields value to "myValue" in case of String.
field.set(someObject, "myValue");
}
// Recursive call to check the nested fields of this field object.
doMagicToFields(
// We actually get the field object here.
field.get(someObject)
);
}
}
}
答案 1 :(得分:1)
要查找内部类MyOuterClass.class.getClasses()
,您可以开始使用,但只会提供一个级别的可见性。您需要遍历这些内部类(例如,SomeInnerClass.class.getClasses()
)以检查它们是否自己有内部类。
获得课程列表之后,只需SomeClass.class.getMethods()
即可获得所有方法的列表。
for(Class<?> clazz : OuterClass.class.getClasses()) {
for(Method method : clazz.getMethods()) {
if(method.getAnnotation(ExcelColumn.class) != null) {
System.out.println(clazz.getName() + "." + method.getName());
}
}
}