Skip to content

Instantly share code, notes, and snippets.

@qmx
Created May 6, 2012 07:19
Show Gist options
  • Save qmx/2620752 to your computer and use it in GitHub Desktop.
Save qmx/2620752 to your computer and use it in GitHub Desktop.
class A {
public Object foo;
public Object bar;
public Object get(String propertyName) {
// hashmap lookup for the rest of the properties
}
}
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;
}
}
@qmx
Copy link
Author

qmx commented May 6, 2012

direct field access for fields, method access for the rest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment