31.7 C
New York
Wednesday, August 28, 2024

Higher than reflection: Utilizing technique handles and variable handles in Java




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

Discover we’re once more instantly working with the metadata of the thing, like its class and the sphere on it. We will manipulate the accessibility of the sphere with setAccessible (that is thought-about dangerous as a result of it would alter the restrictions that have been placed on the goal code as written). That is the important a part of making that non-public subject seen to us.

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


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 personal. There’s additionally a generic lookup(), which can respect the entry modifiers, so it’s safer however gained’t discover the personal subject.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles