Take a look at my code here:
import java.util.function.Function;
public class StaticArgumentsTest {
static Function<String, String> staticConsumer(String testValue) {
return (st) -> testValue + " and " + st;
}
static final Function<String, String> aStaticConsumer =
staticConsumer("Static String Example Value");
public static void main(String[] args) {
System.out.println(StaticArgumentsTest.aStaticConsumer.apply("Dynamic String Example Value"));
}
}
We've got some legacy code with many of these sorts of functional interface implementations and I would rather have this code in a more manageable state like a database rather than have these settings in plain java code. So my question is, is it possible to find the string value "Static String Example Value" you see above using reflection? I would probably rather do this than just write my own java code parser for this stuff, but as far as I can tell I'm stuck doing that.
Of course, this is highly implementation dependent and not recommended for production code, but for a one-time conversion task, it will work with ordinary Reflection operations and the current implementation of HotSpot/OpenJDK:
public class StaticArgumentsTest {
static Function<String, String> staticConsumer(String testValue) {
return (st) -> testValue + " and " + st;
}
static final Function<String, String> aStaticConsumer =
staticConsumer("Static String Example Value");
public static void main(String[] args) {
System.out.println(aStaticConsumer.apply("Dynamic String Example Value"));
getCapturedValues(aStaticConsumer);
}
private static void getCapturedValues(Object instance) {
Field[] f = instance.getClass().getDeclaredFields();
AccessibleObject.setAccessible(f, true);
for(Field field: f) {
System.out.print(field.getName()+" ("+field.getType()+"): ");
try { System.out.println(field.get(instance)); }
catch(ReflectiveOperationException ex) { System.out.println(ex); }
}
}
}
Static String Example Value and Dynamic String Example Value
arg$1 (class java.lang.String): Static String Example Value
Of course, these synthetic fields have no meaningful names, but for a lambda expression which captures only one value, it is obvious, whereas for others, you may use some reasonable heuristics, e.g. based on type or order, to find out which field corresponds to which variable.