gpt4 book ai didi

Java self 反射(reflection)

转载 作者:太空宇宙 更新时间:2023-11-04 12:27:36 24 4
gpt4 key购买 nike

这很奇怪,但我想调用 self 方法。

这是我的抽象类

public abstract class AbstractMapper {
public AbstractMapper(Map<String, String> map) {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field: fields) {
if (field.getAnnotation(Column.class) != null) {
String fName = field.getName();
String rsName = field.getAnnotation(Column.class).name();
StringBuilder sb = new StringBuilder("set")
.append(Character.toUpperCase(fName.charAt(0)))
.append(fName.substring(1));
String mName = sb.toString();

// this.invoke(mName, map.get(fName)); <-- What should I put this here?
}
}
}
public Result getCalculatedValues() {
return xxxx;
}
}

这是我的课

public class NewMachine extends AbstractMapper{
@column(name = machine)
private String machine;

@column(name = temperature)
private Double temperature;

// normal get/set methods

}

现在,我的目标是 AbstractMapper 构造函数迭代所有具有列的字段,并调用其所有相应的 setter。

在这种情况下,我可以传递类似的内容

Map<String, String> map = SomeClass.SomeMethod();
NewMachine m = new NewMachine(map);
Result r = m.getCalculatedValues();

感谢您的帮助。

最佳答案

尝试 getClass().getMethod( mName, field.getType() ).invoke(this, map.get(fName) ) (并处理任何可能的异常)。

此外,请记住有关 getDeclaredFields() 的 JavaDoc:

Returns an array of {@code Field} objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.

如果你有一个层次结构,你还必须获取父类(super class)的字段。

关于Java self 反射(reflection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38197363/

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