Why are classLoader magic values in defineClass() throwing an exception?

梦想的初衷 提交于 2020-01-07 09:28:05

问题


I want to write a classLoader that can help me implement customized classes and ultimately a whole component at run time. Right now I'm in process of loading the class.

I'm trying to load this role.java file. However when I get to this part of the code:

myClass = super.defineClass(className, classData, 0, classData.length);

I get this exception:

Exception in thread "main" java.lang.ClassFormatError: Incompatible magic value 1885430635 in class file C:\Users\ARIFAH\Downloads\Compressed\eUML2 free version\with classLoader code\2\archetypedComponentWithNull\src\aC\Role/java

at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at customCL.customClassLoader.loadClass(customClassLoader.java:116)
at java.lang.ClassLoader.loadClass(Unknown Source)
at customCL.customClassLoader.main(customClassLoader.java:145)

I've read posts saying "you need something like OSGi". That would be similar to working on something new from scratch, which I'd like to avoid.

Why am I getting this error?


回答1:


You aren't actually loading a real class file. The magic value of any valid class file is 0xCAFEBABE, and this magic in hex is 0x7061636B.

Notice that if we convert 0x7061636B to ASCII byte by byte, it turns out to be the string "pack". This means that the file you think is a class file actually starts with the string "pack".



来源:https://stackoverflow.com/questions/7752945/why-are-classloader-magic-values-in-defineclass-throwing-an-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!