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

标签 java methods groovy

我有一个名为 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/

相关文章:

java - 如何创建另一个方法中已存在的新对象?

pointers - bytes.Reader,替换底层 []byte 数组

arrays - 在Groovy脚本上查看SQL保存

JavaFX FXML-SceneBuilder-图像可调整大小

java - spring boot 集成测试 - 数据库未使用 @WebMvcTest Autowiring

java - 使用 Gradle 运行 java 小程序

java - Groovy 正则表达式不起作用

java - 想要为我的 java mysql 项目制作安装文件

java - 从字符串中删除选定字符

groovy - 使用 Groovy 和 Jacob 扩展 HP Quality Center