我正在通过 Java 使用反射来解析 groovy 脚本,以从脚本中获取方法。 对于我的项目,我需要所有非合成和公共(public)的方法。
GroovyScriptEngine groovyScriptEngine = new GroovyScriptEngine(scriptFile.getAbsolutePath());
Class<GroovyObject> scriptClass = groovyScriptEngine.loadScriptByName(scriptFile.getName());
// some code
GroovyObject groovyObject = scriptClass.getConstructor().newInstance();
if (groovyObject != null) {
Method[] declaredMethods = groovyObject.getClass().getDeclaredMethods();
return Arrays.stream(declaredMethods)
.filter(m -> !m.isSynthetic() && Modifier.isPublic(m.getModifiers()))
.collect(Collectors.toList());
}
对于普通的 Groovy 类,这将返回所有 getter 和 setter 以及公共(public)用户定义方法。
例如:
class MyGroovyClass {
def int number = 1
int add(int anotherNumber) {
return number + anotherNumber
}
}
解析groovy类返回getNumber、setNumber、addNumber。 对于空的 groovy 类(没有字段,没有声明的方法),这将返回一个空列表。
但是对于空脚本(=完全空的文件),这将返回方法“run”和“main”。
为什么从空的 groovy 脚本中获取和过滤(对于非合成和公共(public))方法会返回“run”和“main”? 如何过滤这两种方法? (或者我可以早点发现这个情况吗?)
最佳答案
嗯,groovy 脚本必须编译成在 JVM 上运行并具有入口点的东西,显然它只是一个带有 main
方法的类。
所以基本上groovy脚本被编译成一个类,脚本的主体被复制到run
方法中,并且main
方法必须被指定为入口点我已经解释过了。在某些时候 main 将调用 run(间接)。
因此,对于每个脚本,您都会获得这些方法。
其描述见groovy documentation (参见3.2.脚本类
段落)
关于java - Groovy 方法 isSynthetic 对于 run 和 main 为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59961474/