mardi 3 décembre 2019

Java class method with Class and Field as parameters

How can i create a method that accepts Class and Field as parameters? Like this:

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
    }
}

Want to have correct references on compile stage, not at runtime.





Aucun commentaire:

Enregistrer un commentaire