ClassLoader.defineClass 上出现 NoClassDefFoundError (名称错误)
我有一个类文件,我正在通过对 ClassLoader.defineClass 的反射调用从中读取字节并定义到 Class 对象中。
我收到的 NoClassDefFoundError 消息是:
Caused by: java.lang.NoClassDefFoundError: com/foo/sub/Foo (wrong name: com.foo.sub.Foo)
类文件是使用包“com.foo.sub”编译的,因此该类的完全限定名称将是“com.foo.sub.Foo”
的调用:
byte[] fileBytes;
//... read file
Method defineClass;
//... initialize and prepare Method for reflective call
Class clazz = defineClass.invoke("com.foo.sub.Foo", fileBytes, 0, fileBytes.length);
对DefineClass javadocs 状态(关于 defineClass 的 name 参数):“name - 类的预期名称,如果未知,则使用 '.'而不是'/'作为分隔符并且没有尾随.class后缀。”
我不明白为什么抛出异常以及消息应该指示什么。任何帮助表示赞赏。
I have a class file that I am reading the bytes from and defining into a Class object via a reflective call to ClassLoader.defineClass.
The NoClassDefFoundError message that I'm receiving is:
Caused by: java.lang.NoClassDefFoundError: com/foo/sub/Foo (wrong name: com.foo.sub.Foo)
The class file was compiled with the package "com.foo.sub" so the fully qualified name of the class would be "com.foo.sub.Foo"
The call to defineClass:
byte[] fileBytes;
//... read file
Method defineClass;
//... initialize and prepare Method for reflective call
Class clazz = defineClass.invoke("com.foo.sub.Foo", fileBytes, 0, fileBytes.length);
The javadocs state (regarding the name parameter of defineClass): "name - The expected name of the class, or null if not known, using '.' and not '/' as the separator and without a trailing .class suffix."
I don't understand why the exception is being thrown and what the message is supposed to indicate. Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 该方法的文档,如果您指定一个名称(在您的情况下是 com.foo.sub.Foo ),该名称与该类定义自身具有的名称(在您的 fileBytes 内)不匹配。
要找出正确的名称,请尝试类似的内容
(应该打印类似
class com.foo.sub.Foo
的内容)。According to that method's documentation, it will raise
NoClassDefFoundError
if you specify a name (in your casecom.foo.sub.Foo
) that doesn't match the name that the class defines itself as having (inside yourfileBytes
).To find out the correct name, try something like
(which should print something like
class com.foo.sub.Foo
).