据我所知,方法引用既可以静态使用,也可以与包装对象实例一起使用,例如:
public class MethodReferencesExampleTest {
class Example {
private String variable;
public Example(String variable) {
this.variable = variable;
}
public String getVariable() {
return variable;
}
}
@Test
public void shouldBeAbleToUseBothClassAndInstanceMethodReference() {
Example objectUnderTest = new Example("variable");
useClassMethodReference(Example::getVariable, objectUnderTest);
useInstanceMethodReference(objectUnderTest::getVariable);
}
private <T> void useClassMethodReference(Function<T, String> methodReference, T object) {
System.out.println("Class reference call result = " + methodReference.apply(object));
}
private void useInstanceMethodReference(Supplier<String> methodReference) {
System.out.println("Instance reference call result = " + methodReference.get());
}
}
我想要做的是提取实例方法引用并以某种方式将其转换为类方法引用,以便我可以将它应用于同一个类的不同对象,如:
private <T> void useInstanceMethodReferenceOnDifferentObjectThanItsSource(Supplier<String> instanceMethodReference, T object) {
Function<T, String> classMethodReference = /* some magical conversion */ instanceMethodReference;
System.out.println("Instance reference call result = " + classMethodReference.apply(object));
}
有可能吗?像使用cglib
甚至是阴暗的#34; hacks&#34;是一个可以接受的答案。