I use method defineClass()
from the ClassLoader
to define a class from the byte array. I fetch this method using reflection:
ClassLoader.class.getDeclaredMethod(
"defineClass", String.class, byte[].class, int.class, int.class);
Java10 complains about reflective usage of defineClass
.
What should I use instead?
MethodHandles.Lookup.defineClass appears to be the blessed replacement. Note, however, that the class you are defining must be in the same runtime package as the lookup's lookup class. You will not be able to create classes in packages that exist in other modules, a restriction that previous methods did not have. Depending on your use case, those issues may or may not arise.
For follow-up reading, Rafael Winterhalter has blogged about the new restrictions in the context of his work with Byte Buddy. If you are technical enough to understand the issues surrounding arbitrary runtime class definitions, it may be of interest to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With