gpt4 book ai didi

java - 拉取所有带有注解的字段(包括一个对象中的字段在另一个对象中和内部类中的字段)

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:44:00 25 4
gpt4 key购买 nike

您好,我正在创建一个自定义 Excel 解析编码器工具,您可以引用这个: 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;
}
}

最佳答案

以下类实现了 AnnotatedElement 接口(interface):

  • AccessibleObject
  • 构造函数
  • 字段
  • 方法

然后您可以在所述类的对象实例上调用:

<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.getType()){
// 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)
);
}

}
}

关于java - 拉取所有带有注解的字段(包括一个对象中的字段在另一个对象中和内部类中的字段),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29700918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com