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

Published on:


Class> clazz = objectInstance.getClass(); 
Area area = clazz.getDeclaredField("title"); 
area.setAccessible(true); 
String worth = (String) area.get(objectInstance);
System.out.println(worth); // prints “John Doe”

Discover we’re once more straight working with the metadata of the article, like its class and the sphere on it. We are able to manipulate the accessibility of the sphere with setAccessible (that is thought of dangerous as a result of it’d alter the restrictions that had been placed on the goal code as written). That is the important a part of making that non-public area seen to us.

Now let’s do the identical factor utilizing variable handles:

- Advertisement -

Class&gtl clazz = objectInstance.getClass();
VarHandle deal with = MethodHandles.privateLookupIn(clazz,   
  MethodHandles.lookup()).findVarHandle(clazz, "title", String.class);
String worth = (String) deal with.get(objectInstance);
System.out.println(value4); // prints "John Doe"

Right here, we use privateLookupIn as a result of the sphere is marked non-public. There’s additionally a generic lookup(), which is able to respect the entry modifiers, so it’s safer however gained’t discover the non-public area.

See also  FTC Chair Lina Khan shares how the agency is looking at AI
- Advertisment -

Related

- Advertisment -

Leave a Reply

Please enter your comment!
Please enter your name here