如何创建一个接受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);

  ask by lanmaster translate from so

本文未有回复,本站智能推荐: