【发布时间】:2019-12-03 10:08:01
【问题描述】:
如何创建一个接受 Class 和 Field 作为参数的方法?像这样:
List<SomeClassEntity> list = ...;
// Service to make useful things around a list of objects
UsefulThingsService<SomeClassEntity> usefulThingsService = new UsefulThingsService<>();
// Maybe invoke like this. Did't work
usefulThingsService.makeUsefulThings(list, SomeClassEntity.class, SomeClassEntity::getFieldOne);
// or like this. Will cause delayed runtime erros
usefulThingsService.makeUsefulThings(list, SomeClassEntity.class, "fieldTwo");
public class SomeClassEntity {
Integer fieldOne = 10;
Double fieldThree = 0.123;
public Integer getFieldOne() {
return fieldOne;
}
public void setFieldOne(Integer fieldOne) {
this.fieldOne = fieldOne;
}
public Double getFieldThree() {
return fieldThree;
}
public void setFieldThree(Double fieldThree) {
this.fieldThree = fieldThree;
}
}
public class UsefulThingsService<T> {
public void makeUsefulThings(Class<T> someClassBClass, String fieldName) {
// there is some code
}
}
希望在编译阶段有正确的引用,而不是在运行时。
更新: 我需要看起来比这更方便的代码:
Field fieldOne = null;
try {
fieldOne = SomeClassEntity.class.getDeclaredField("fieldOne");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
usefulThingsService.makeUsefulThings(SomeClassEntity.class, fieldOne);
对于接下来的澄清,我深表歉意。
更新 2:
- 该服务将列表与之前的列表进行比较,仅显示对象(列表项)的更改字段,并更新原始列表中对象中的这些字段。
- 目前我在实体的字段上使用注释,它实际上是实体的 ID,当我需要更新源列表中的实体字段时,该 ID 用于检测相同的实体(旧的和新的)。
- 服务检测带注释的字段并将其用于下一个更新过程。
- 我想拒绝使用注释并直接在服务的构造函数中提供一个字段。或者使用其他可以在编译阶段建立类和字段之间关系的东西。
【问题讨论】:
-
public void myMethod(Class type, Field f) { } 你去...
-
问题不清楚。
-
也许重新考虑问题,如果你能以不同的方式解决它,例如使用访问器函数,也许还有一些 Java 8 Lambdas
-
@JonasMichel 更新
标签: java class methods reflection field