我无法相信我必须提出这个问题,这真的令人困惑。这个问题的目标是找出为什么和/或找到一种更简单的方法(而不是反射)来获得正确的结果。
我通过URLClassLoader
从目录和jar文件加载了一些类文件,我想转储所有类名及其声明的方法。无法初始化类(请参阅false
),因为如果在这些类中运行任何代码,可能会由于某些缺少的依赖项而抛出异常。我在尝试输出类名时遇到了这个问题。
我缺少什么,我如何解决Groovy的魔法,只需在对象(类型getName
)上调用一个方法(称为java.lang.Class
)而不进行反射?有人也请指出为什么这样工作的规范。
这是我的迷你测试的输出(见下文)和我的评论:
.name // magically initializes class X and calls X.get("name")
name and Y
.getName() // tries to reload class Y in another ClassLoader and initialize it
X and thrown SHOULD NOT INIT
["name"] // this is just plain magic! What a Terrible Failure :)
name and thrown SHOULD NOT INIT
reflection // obviously works, becase it's really explicit
X and Y
将参数类型(Class<?> c ->
)更改为明确的测试闭包没有任何区别。
new File("X.java").write('''
public class X {
public static String get(String key) {
return key;
}
}
''');
new File("Y.java").write('''
public class Y {
static {
if (true) // needed to prevent compile error
throw new UnsupportedOperationException("SHOULD NOT INIT");
}
}
''');
print 'javac X.java Y.java'.execute().err.text;
def test = { String title, Closure nameOf ->
URL url = new File(".").toURI().toURL();
// need a new ClassLoader each time because it remembers
// if a class has already thrown ExceptionInInitializerError
ClassLoader loader = java.net.URLClassLoader.newInstance(url);
// false means not to initialize the class.
// To get the name of the class there's no need to init
// as shown in the reflection test.
// Even fields and methds can be read without initializing,
// it's essentially just parsing the .class file.
Class x = Class.forName("X", false, loader);
Class y = Class.forName("Y", false, loader);
println()
println title
try {
print nameOf(x)
} catch (Throwable ex) {
print "thrown " + ex.cause?.message
}
print " and "
try {
print nameOf(y)
} catch (Throwable ex) {
print "thrown " + ex.cause?.message
}
println()
}
test '.name', { c -> c.name; }
test '.getName()', { c -> c.getName(); }
test '["name"]', { c -> c["name"] }
test 'reflection', { c -> java.lang.Class.class.getDeclaredMethod("getName").invoke(c); }
答案 0 :(得分:0)
对于invokedynamic端口,我可以给出一个明确的答案:绕过一个JVM错误,其中JVM调用了一个类的静态方法,而根本没有调用clinit。
至于另一部分....这将是提交https://github.com/apache/incubator-groovy/commit/0653ddc15ec0215f2141159a71c1b12d8d800dbe#diff-59caa62540f88da51c8c91c6656315d5不确定为什么塞德里克这样做。假设JVM按预期工作,则不需要这样做......