Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to use instead of `defineClass` in Java10?

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?

like image 769
igr Avatar asked May 22 '18 15:05

igr


1 Answers

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.

like image 121
Matt Leidholm Avatar answered Sep 23 '22 12:09

Matt Leidholm