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

标签 java methods reflection groovy gradle

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

背景故事

我通过 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); }

最佳答案

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

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

关于java - 如何在 Groovy 中调用一个简单的 getter 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29880907/

相关文章:

java - Guice 的宗旨

javascript - 多条路由 Backbone 上的相同事件

java - 有没有办法判断运行时类型是否被删除

java - Java 反射包装器代码生成器?

scala 反射,使用 asInstanceOf 进行类型转换

java - ActiveJDBC 和 Junit 中的动态检测问题

Java 集合逻辑/过度编码问题

java - 从 ArrayList 中删除偶数

java - Java中简单的数字计数器方法

c++ - 在 C++ 中使用方法作为变量