Last active
November 2, 2023 04:58
-
-
Save vhagedorn/fecb03874585a6bbe25552f42f61ec42 to your computer and use it in GitHub Desktop.
Fast reflective field access
This file contains 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
import java.lang.invoke.MethodHandle; | |
import java.lang.invoke.MethodHandles; | |
import java.lang.reflect.Field; | |
/** | |
* @author vadim | |
*/ | |
public class FieldAccess { | |
private final Field field; | |
private final MethodHandle set, get; | |
private final RuntimeException err(String s, Throwable t) { | |
return new RuntimeException("Unable to "+s+" for field "+field.getDeclaringClass().getCanonicalName()+"#"+field.getName(), t); | |
} | |
public FieldAccess(Field field) { | |
this.field = field; | |
MethodHandles.Lookup lookup; | |
try { | |
lookup = MethodHandles.privateLookupIn(field.getDeclaringClass(), MethodHandles.lookup()); | |
} catch (Exception e) { | |
throw err("create a private lookup", e); | |
} | |
try { | |
set = lookup.unreflectSetter(field); | |
} catch (Exception e) { | |
throw err("unreflect setter", e); | |
} | |
try { | |
get = lookup.unreflectGetter(field); | |
} catch (Exception e) { | |
throw err("unreflect getter", e); | |
} | |
} | |
public Object get(Object instance) { | |
try { | |
return get.invoke(instance); | |
} catch (Throwable t) { | |
throw err("invoke getter", t); | |
} | |
} | |
public void set(Object instance, Object value) { | |
try { | |
set.invoke(instance, value); | |
} catch (Throwable t) { | |
throw err("invoke setter", t); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment