我有一个名为 sample.groovy
的 groovy 文件,其中包含不同的方法:
class sample {
def doOperation()
{
println("Inside doOperation()")
}
def setData(String str)
{
println("Incoming data : " + str)
}
}
我只定义了两个方法:doOperation()
和 setData()
,我只想列出这两个方法。
我使用了反射并尝试使用 getDeclaredMethods()
列出方法。但它列出了上面的方法和方法,如:setProperty
、getProperty
、setMetaClass
等。
我只想列出这个特定文件中定义的方法。
最佳答案
根据 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/