184. Creating a hidden class
Let’s assume that our hidden class is named InternalMath
and is as simple, as follows:
public class InternalMath {
public long sum(int[] nr) {
return IntStream.of(nr).sum();
}
}
As we mentioned in the previous problem, hidden classes have the same class loader as the lookup class, which can be obtained via MethodHandles.lookup()
, as follows:
MethodHandles.Lookup lookup = MethodHandles.lookup();
Next, we must know that Lookup
contains a method named defineHiddenClass(byte[] bytes, boolean initialize, ClassOption... options)
. The most important argument is represented by the array of bytes that contain the class data. The initialize
argument is a flag specifying if the hidden class should be initialized or not, while the options
argument can be NESTMATE
(the created hidden class becomes a nestmate of the lookup class and has access to all the private members in the same nest) or STRONG
(the created hidden class can be unloaded...