gpt4 book ai didi

java - 获取有关实例变量名称的内部 setter 信息

转载 作者:太空宇宙 更新时间:2023-11-04 06:08:31 26 4
gpt4 key购买 nike

是否可以在对象的setter中获取当前实例的变量名?

类似这样的事情

public class Class {
private DataType dataType;
}

public class DataType {

public void setValue(String value) {
if (variableName is 'dataType') {
this.value = value;
} else {
this.value = null;
}
}
}

如果无法使用标准实用程序,那么是否可以创建某种注释来存储变量名称,然后在 setter 中使用它?

当我尝试这样做时 - 注释为空。我创建注释

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface FieldName {

String fieldName();
}

然后我将其添加到字段

public class Class {
@FieldName(fieldName = "dataType")
private DataType dataType;
}

当我尝试在 DataTypegetter 中获取它时 - 注释 FieldName 为空。

private String wrapGetter(String requiredFieldName, String dataTypeField) {
FieldName fieldName = this.getClass().getAnnotation(FieldName.class);
if (fieldName.fieldName().equals(requiredFieldName)) {
return dataTypeField;
} else {
return dataTypeField;
}
}

最佳答案

您尝试执行的操作存在一些问题:

  1. 您的RetentionPolicy已将其设置为CLASS,这意味着类加载器将丢弃它,并且它将在运行时不可用。您应该改用 RetentionPolicy.RUNTIME

  2. this.getClass().getAnnotation(FieldName.class) 将为您提供类注释。

在下面的示例中,注释不为空,您可以在 setValue 方法中获取 "example" 字符串:

@FieldName(fieldName = "example")
public class DataType {

public void setValue(String value) {
System.out.println(this.getClass().getAnnotation(FieldName.class));
}

}

public static void main(String[] args) {
new DataType().setValue("ignored");
}

这还需要将注释的目标更改为@Target(ElementType.TYPE)

  • 变量或字段名只是一个引用,它指向内存中的某个对象。您可以对同一对象有多个引用。虽然您可以注释不同类中的字段,但这将是局部变量和参数的问题 - 很难说,因为我不知道您想要实现什么。
  • 有问题的示例:

    public class ClassOne {
    @FieldName(fieldName = "dataType")
    private DataType a;
    }

    public class ClassTwo {
    @FieldName(fieldName = "dataType")
    private DataType b;
    }

    public class ClassThree {
    public void doSomething() {
    DataType c = new DataType();
    }
    }

    public class ClassFour {
    public void doSomething(DataType d) {
    // ...
    }
    }

    通常,这一切都归结为类的实例没有关于如何引用它的信息。但是,对于该字段,封闭类具有此信息。考虑将您的方法移至该类中。您可以在没有任何注释的情况下处理这个问题:

    public class DataType {
    public void setValue(String value) {
    // ...
    }
    }

    public class ClassOne {
    private DataType dataType;

    public void setDataTypeValue(String value) {
    dataType.setValue(value);
    }
    }

    public class ClassTwo {
    private DataType anyOtherFieldName;

    public void setDataTypeValue(String value) {
    anyOtherFieldName.setValue(null);
    }
    }

    设置 null 并忽略参数的 setter 非常具有误导性,您的 IDE 应该向您发出有关未使用参数的警告,这不是没有原因的。我认为您应该考虑重新设计,但在不了解更多细节的情况下,我无法为您提供进一步的建议。

    与其解决问题,不如尝试解决问题的原因。

    关于java - 获取有关实例变量名称的内部 setter 信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29028480/

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