有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

列出Java中Groovy类的声明方法

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

class sample {

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

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

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

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

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


共 (3) 个答案

  1. # 1 楼答案

    您应该在下面尝试只获取您的方法,而不是继承的方法:-

    def myMethods = MyClass.declaredMethods.findAll { !it.synthetic }
    

    希望它能帮助你……:)

  2. # 2 楼答案

    根据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 streams API:

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

    你所要求的并没有什么意义

    你看,Java语言对Groovy语言一无所知

    关键是Groovy源代码将在某个时刻编译成JVM字节码

    这意味着:与Java语言相比,Groovy“添加”的所有东西。。。最后,表示为JVM字节码

    换句话说:groovy编译器实现了它的“魔力”(例如通过添加各种方法);所有这一切都进入了最后阶段。类文件。然后当你“调查”这件事的时候。班你把所有的东西都放进去了。因为“java反射”没有“这个方法实际上是由groovy程序员编写的”和“这个方法是由groovy转换过程添加的”的概念

    长话短说:如果有的话,您需要研究事物的常规方面的机制;因为只有在那里你才能知道“sample”有这两种方法