public class MethodReferenceTest {
@Test
public void testMethodReference() throws Exception {
new PropertyReferencer<>( Foo.class ).printProperty( Foo::getBar );
}
private interface Foo {
public String getBar();
}
private static class PropertyReferencer<T> {
private final T proxy;
@SuppressWarnings("unchecked")
public PropertyReferencer(Class<T> type) {
InvocationHandler handler = new MethodNameRetrievalHandler();
proxy = (T) Proxy.newProxyInstance( type.getClassLoader(), new Class<?>[] { type }, handler );
}
private void printProperty(Function<T, ?> s) {
String methodName = (String) s.apply( proxy );
System.out.println( "Passed property is: " + methodName );
}
}
private static class MethodNameRetrievalHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.getName();
}
}
}