在 Java10 中使用什么来代替`defineClass`? [英] What to use instead of `defineClass` in Java10?

查看:49
本文介绍了在 Java10 中使用什么来代替`defineClass`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 ClassLoader 中的方法 defineClass() 从字节数组中定义一个类.我使用反射获取此方法:

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 抱怨 defineClass 的反射使用.

Java10 complains about reflective usage of defineClass.

我应该用什么代替?

推荐答案

MethodHandles.Lookup.defineClass 似乎是幸运的替代品.但是请注意,您定义的类必须与查找的查找类位于同一个运行时包中.您将无法在其他模块中存在的包中创建类,这是以前的方法没有的限制.根据您的用例,这些问题可能会出现,也可能不会出现.

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.

对于后续阅读,拉斐尔温特哈尔特 在与 Byte Buddy 合作的背景下,已经在博客中讨论了 的新限制.如果您的技术足够了解围绕任意运行时类定义的问题,那么您可能会感兴趣.

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.

这篇关于在 Java10 中使用什么来代替`defineClass`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆