【问题标题】:How to check whether a Groovy class overrides a parent's method如何检查 Groovy 类是否覆盖了父类的方法
【发布时间】:2014-03-24 22:45:38
【问题描述】:

我有两个 Groovy 类,Child1Child2,它们派生自抽象父类 Parent。父类实现了三个方法,只是参数不同(即方法名相同)。

现在我有一个子类的实例。任务是检查该对象的类是否实现(覆盖)一个或多个父类方法。

我尝试在子类对象上使用 Groovy 的 Inspector。这给了我所有方法的列表,但我不确定如何读取输出。特别是我不明白我正在寻找的方法是在子类中实现还是仅在父类中实现。

谁能帮我解决这个问题,我可能需要另一种自省方式吗?

【问题讨论】:

    标签: groovy introspection


    【解决方案1】:

    希望这会有所帮助。我仍然觉得有一种更时髦的方式。尝试使用collectInheritedMethods() 看看你是否得到了你想要的。我故意想要返回匹配方法的列表而不仅仅是一个标志,因为您还可以看到从超类实现的方法,列表中的 Groovy 真相 (if(collectInheritedMethods(..))) 足以进行标记。

    abstract class Parent {
        void method1() { println "No Param" }
        void method1( def a ) { println "param: $a" }
        void method1( List a, Map b ) { println "param: $a and $b" }
    }
    
    class Child extends Parent {
        void method1() { println "A: no param" }
        void method1( def a ) { println "A: param $a" }
        void method1( def a, def b ) { println "A: param $a and $b" }
    }
    
    List collectInheritedMethods( Class parent, Class child ) {
        List inheritedMethods = [] 
        def parentMethods = parent.declaredMethods.findAll { !it.synthetic }
        def childMethods = child.declaredMethods.findAll { !it.synthetic }
    
        for( chMet in childMethods ) {
            for( paMet in parentMethods ) {
                if( chMet.name == paMet.name && 
                      chMet.parameterTypes == paMet.parameterTypes && 
                         chMet.returnType == paMet.returnType ) {
    
                    inheritedMethods << child.getMethod( chMet.name, 
                                                        chMet.parameterTypes )
                                             .toGenericString()
    
                    //if only a flag is required to check if method implemented
                    //flag = true
                    //break
                }
            }
        }
    
        //Groovier way
        /*inheritedMethods = childMethods.findAll { chMet -> 
            parentMethods.findAll { paMet -> 
                chMet.name == paMet.name && 
                    chMet.parameterTypes == paMet.parameterTypes && 
                        chMet.returnType == paMet.returnType 
            } 
        }*/
    
        inheritedMethods
    }
    
    assert collectInheritedMethods( Parent, Child ) == 
           ["public void Child.method1()", 
            "public void Child.method1(java.lang.Object)"]
    

    【讨论】:

      【解决方案2】:

      所以我最终得到了这个解决方案,它正是我想要的:

      def pattern = ~/^public void ... $/
      for(method in obj.metaClass.methods.findAll { it ==~ pattern })
      {
          /* Do some stuff... */
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-06
        • 1970-01-01
        • 2013-07-13
        • 2011-04-17
        • 2013-03-26
        相关资源
        最近更新 更多