Created
May 6, 2012 07:19
-
-
Save qmx/2620752 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class A { | |
public Object foo; | |
public Object bar; | |
public Object get(String propertyName) { | |
// hashmap lookup for the rest of the properties | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Test { | |
@Test | |
public void testIt(){ | |
Object target = new A(); | |
String prop = "foo"; | |
MethodHandle test = Binder | |
.from(boolean.class, target.getClass(), String.class) | |
.convert(boolean.class, Object.class, String.class) | |
.invokeStatic(lookup(), Test.class, "hasNativeProp"); | |
// blows if field doesn't exist | |
MethodHandle fieldHandle = Binder.from(Object.class, target.getClass(), String.class) | |
.drop(1) | |
.getField(lookup(), prop); | |
// blows if method doesn't exist | |
MethodHandle getterHandle = Binder.from(Object.class, target.getClass(), String.class) | |
.invokeVirtual(lookup(), "get"); | |
MethodHandle handle = Binder.from(Object.class, Object.class, String.class) | |
.branch(test, fieldHandle, getterHandle); | |
System.out.println(handle.invoke(target, prop)); | |
} | |
public static boolean hasNativeProp(Object obj, String name) { | |
try { | |
obj.getClass().getDeclaredField(name); | |
return true; | |
} catch (NoSuchFieldBlah e) { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
direct field access for fields, method access for the rest