我正在处理的基于JVM的编程语言的编译器使用此代码在编译后运行指定的main
方法:
URL url = DyvilCompiler.config.outputDir.toURI().toURL();
Class c = Class.forName(mainType, false, new URLClassLoader(new URL[] { url }, ClassLoader.getSystemClassLoader()));
Method m = c.getMethod("main", String[].class);
m.invoke(null, new Object[] { args });
但是,在编译此代码时:
package dyvil.test
// some uninteresting import stuff
public class Main
{
@ArrayConvertible
case class IntVector([int] ints = [ 1, 2 ])
public static void main([String] args)
{
println(IntVector())
println([ 1, 2, 3 ] as IntVector)
}
}
ClassLoader失败,内部类(实际上是嵌套的static
类):
java.lang.ClassFormatError: Illegal class name "Ldyvil/test/Main$IntVector;" in class file dyvil/test/Main$IntVector
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:367)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at dyvil.test.Main.main(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at dyvil.tools.compiler.util.TestThread.run(TestThread.java:32)
请注意,为Main dyvil/test/Main
和IntVector dyvil/test/Main$IntVector
生成的类文件确实定义了内部类关系:
Inner classes:
[inner class info: #2 dyvil/test/Main$IntVector, outer class info: #7 dyvil/test/Main
inner name: #9 IntVector, accessflags: 8 static]
Enclosing Method: #7 #0 dyvil/test/Main
Ldyvil/test/Main$IntVector;
签名有什么问题?此外,将输出目录添加到类路径并将代码更改为
Class c = Class.forName(mainType)
一切顺利,没有任何错误。
编辑 :这不仅会导致JVM出现问题,而且当通过import
在Eclipse中使用这样的类时,代码完成停止完全工作。