如何在Groovy中调用一个简单的getter方法?

How to call a simple getter method in Groovy?

我不敢相信我必须问这个问题,这真的很令人困惑。这道题的目的是弄清楚为什么 and/or找到一种更简单的方法(比反射)得到正确的结果。

背景故事

我通过 URLClassLoader 从目录和 jar 文件中加载了一些 class 文件,我想转储所有 class 名称及其声明的方法. classes 无法初始化(请参阅 false),因为如果在这些 classes 中运行任何代码,可能会由于缺少某些依赖项而引发异常。我 运行 在尝试仅输出 class 名称时遇到了这个问题。

问题

我错过了什么,我怎样才能绕过 Groovy 的魔力,而只是简单地调用一个对象(java.lang.Class 类型)的方法(称为 getName)而不用反射?也请有人指出规范,说明为什么这样工作。
这是我的迷你测试的输出(见下文)和我的评论:

.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); }

对于 invokedynamic 端口,我可以给出一个明确的答案:绕过一个 JVM 错误,在该错误中 JVM 调用了 class 的静态方法,而根本没有调用 clinit。

至于另一部分....这将是提交 https://github.com/apache/incubator-groovy/commit/0653ddc15ec0215f2141159a71c1b12d8d800dbe#diff-59caa62540f88da51c8c91c6656315d5 不确定塞德里克为什么这样做。假设 JVM 正常工作,则不需要...