gpt4 book ai didi

java - 列出 Java 中 Groovy 类的已声明方法

转载 作者:行者123 更新时间:2023-11-30 08:36:39 25 4
gpt4 key购买 nike

我有一个名为 sample.groovy 的 groovy 文件,其中包含不同的方法:

class sample {

def doOperation()
{
println("Inside doOperation()")
}

def setData(String str)
{
println("Incoming data : " + str)
}
}

我只定义了两个方法:doOperation()setData(),我只想列出这两个方法。

我使用了反射并尝试使用 getDeclaredMethods() 列出方法。但它列出了上面的方法和方法,如:setPropertygetPropertysetMetaClass等。

我只想列出这个特定文件中定义的方法。

最佳答案

根据 JLS 13.1.7 ,生成的“Groovy”方法应标记为合成方法:

Any constructs introduced by a Java compiler that do not have a corresponding construct in the source code must be marked as synthetic, except for default constructors, the class initialization method, and the values and valueOf methods of the Enum class.

考虑到这一点,您可以过滤掉类中的合成方法,只为您提供源代码中的方法:

def methods = sample.declaredMethods.findAll { !it.synthetic }

如果您正在寻找纯 Java 解决方案,您可以执行以下操作:

List<Method> methods = new ArrayList<>();
for (Method m : sample.class.getDeclaredMethods()) {
if (!m.isSynthetic()) {
methods.add(m);
}
}

或者使用 Java 8 流 API:

List<Method> methods = Arrays.stream(sample.class.getDeclaredMethods())
.filter(m -> !m.isSynthetic())
.collect(Collectors.toList());

关于java - 列出 Java 中 Groovy 类的已声明方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37614276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com