Issue
I have the following implementation:
private SomeWritter someWritter(String someArgument) {
SomeWritter.Builder builder = SomeWritter.builder(someArguments);
builder = builder.addColumn("colName1", TargetClass::getArg1)
builder = builder.addColumn("colName2", TargetClass::getArg2)
return builder.build();
}
private Builder<T> addColumn(String colName, ToDoubleFunction<T> getter){
//implementation goes here
}
my issue is that I need to iterate over the addColumns call, something among these lines:
private void SomeWritter(String someArgument) {
SomeWritter.Builder builder = SomeWritter.builder(someArguments);
for (Field field : getFilteredFieldsFromClass(TargetClass.class)) {
builder = builder.addColumn(field.getName(), [SOMEHOW GET THE REF TO GETTER HERE])
}
return builder.build();
}
in order to get the refference to the getter, I tryed to do TargetClass.class.getMethod("getArg1", ...);
this works, but I have a Method, not a ToDoubleFunction.
I need to somehow get that ToDoDoubleFunction, programatically, I want to do the same that the TargetClass:: does, dinamically, not harcoded. any ideas ?
Solution
import java.lang.reflect.Field;
public class Main {
static class Example{
double arg1;
int arg2;
}
interface Foo<T>{
double toDouble(T example);
}
public static void addColumn(Foo<Example> foo){
//do nothing
}
public static void main(String[] args) {
final var example = new Example();
for(Field field: Example.class.getDeclaredFields()){
addColumn(example1 -> {
try {
return (double) field.get(example1);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
}
}
}
That code iterates over all fields of the Example class and uses the reflection inside a lambda. Side Note. Intellij can replace method references with lambda when you click alt+enter when cursor is on them (Windows).
Answered By - Alex
Answer Checked By - Candace Johnson (JavaFixing Volunteer)