I'm currently stuck figuring out how method references works. This is what I'm trying to achieve.
User user = new User(...);
user.getValue(ADerived::getPropertyFromA);
user.getValue(BDerived::getPropertyFromB);
ADerived and BDerived are as following (simplified)
public abstract class Base { }
public class ADerived extends Base {
private static final String A_OUTPUT = "Test A";
public String getPropertyFromA() {
return A_OUTPUT;
}
}
public class BDerived extends Base {
private static final String B_OUTPUT = "Test B";
public String getPropertyFromB() {
return B_OUTPUT;
}
}
The getPropertyFromX method is not defined in the the Base class on purpose since they differ to much.
In the BaseUser class I save an instance of the subclasses in a map and try to execute the passed method on this instance. Atleast this code compiles but of course doesn't work as expected. Other approaches around Function<>
did not work for me either.
public class User {
public Map<Class, Base> map;
public User(...) {
... creates instances of ADerived and BDerived, puts them into map
}
...
public <R> String getValue(Function<R, String> func) {
return func.apply((R) map.get((R) Base.class));
}
}
This is clearly not working for multiple reasons but I can't figure out a way to get the usage described above.
Is it even realistic to get the described usage? Is there anything I'm missing?
Would love to hear ideas or get some help.