• Mon. Nov 25th, 2024

Better than reflection: Using method handles and variable handles in Java

Byadmin

Aug 30, 2024



Class> clazz = objectInstance.getClass();
Field field = clazz.getDeclaredField(“name”);
field.setAccessible(true);
String value = (String) field.get(objectInstance);
System.out.println(value); // prints “John Doe”

Notice we are again directly working with the metadata of the object, like its class and the field on it. We can manipulate the accessibility of the field with setAccessible (this is considered risky because it might alter the restrictions that were put on the target code as written). This is the essential part of making that private field visible to us.

Now let’s do the same thing using variable handles:

Class&gtl clazz = objectInstance.getClass();
VarHandle handle = MethodHandles.privateLookupIn(clazz,
MethodHandles.lookup()).findVarHandle(clazz, “name”, String.class);
String value = (String) handle.get(objectInstance);
System.out.println(value4); // prints “John Doe”

Here, we use privateLookupIn because the field is marked private. There is also a generic lookup(), which will respect the access modifiers, so it’s safer but won’t find the private field.



Source link