gpt4 book ai didi

Java Reflection - 获取现有对象中的当前字段值

转载 作者:行者123 更新时间:2023-12-01 07:20:15 24 4
gpt4 key购买 nike

我有一个以下类型的构造对象,

public class Form {
private String a;
private String b;
private Boolean c;

public String getA() { return a; }
public void setA (String a) { this.a = a; }
public String getB() { return b; }
public void setB (String b) { this.b = b; }
public Boolean getC() { return c; }
public void setC (Boolean c) { this.c = c; }
}

我正在使用反射来检查现有对象,例如此表单:("testA", "testB", False)

如何获取特定字段的当前值(例如 String b)?

// Assume "form" is my current Form object
Field[] formFields = form.getClass().getDeclaredFields();
if (formFields != null) {
for (Field formField : formFields) {
Class type = formField.getType();
// how do I get the current value in this current object?
}
}

最佳答案

java.lang.reflect.Field的使用方法:

// Necessary to be able to read a private field
formField.setAccessible(true);

// Get the value of the field in the form object
Object fieldValue = formField.get(form);

关于Java Reflection - 获取现有对象中的当前字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40809498/

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