package fcm; import java.lang.reflect.Method; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; public class MethodReferenceTest { public static class TargetClass { public String getFoo() { return foo; } public void setFoo(String foo) { this.foo = foo; } private String foo; } public static class OriginClass { public void setBar(String bar) { this.bar = bar; } public String getBar() { return this.bar; } private String bar; } public static void mapProperty(Object from, Method fromMethod, Object to, Method toMethod) throws IllegalAccessException, InvocationTargetException { toMethod.invoke(to, fromMethod.invoke(from)); } public static void mapField(Object from, Field fromField, Object to, Field toField) { toField.setAccessible(true); fromField.setAccessible(true); try { toField.set(to, fromField.get(from)); } catch (IllegalAccessException e) { throw new RuntimeException("Impossible! We set everything accessible: " + e); } } public static void main(String[] args) throws IllegalAccessException, InvocationTargetException { OriginClass origin = new OriginClass(); origin.setBar("origin mapped as property"); TargetClass target = new TargetClass(); mapProperty(origin, OriginClass#getBar(), target, TargetClass#setFoo(String)); System.out.println(target.getFoo()); origin.setBar("origin mapped as field"); mapField(origin, OriginClass#bar, target, TargetClass#foo); System.out.println(target.getFoo()); } public static void theOldWay() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { OriginClass origin = new OriginClass(); origin.setBar("bar on origin"); TargetClass target = new TargetClass(); // We now want to copy the "bar" property of OriginClass to the "foo" property of the TargetClass Method fromMethod = OriginClass.class.getMethod("getFoo"); Method toMethod = TargetClass.class.getMethod("setFoo", String.class); toMethod.invoke(target, fromMethod.invoke(origin)); System.out.println(target.getFoo()); } public static void theNewWay() throws IllegalAccessException, InvocationTargetException { OriginClass origin = new OriginClass(); origin.setBar("bar on origin"); TargetClass target = new TargetClass(); // We now want to copy the "bar" property of OriginClass to the "foo" property of the TargetClass // The compiler catches this error: Method fromMethod = OriginClass#getFoo(); Method fromMethod = OriginClass#getBar(); Method toMethod = TargetClass#setFoo(String); toMethod.invoke(target, fromMethod.invoke(origin)); System.out.println(target.getFoo()); } public static void withLibrarySupport() { OriginClass origin = new OriginClass(); origin.setBar("bar on origin"); TargetClass target = new TargetClass(); mapField(origin, OriginClass#bar, target, TargetClass#foo); System.out.println(target.getFoo()); } }