【问题标题】:In groovy, is there a way to check if an object has a given method?在 groovy 中,有没有办法检查一个对象是否有给定的方法?
【发布时间】:2018-05-08 17:44:27
【问题描述】:

假设我有一个不确定类型的对象someObj,我想做这样的事情:

def value = someObj.someMethod()

如果不能保证 'someObj' 实现了 someMethod() 方法,如果没有,则返回 null

Groovy 中是否有类似的东西,或者我需要用instanceof 检查将其包装在 if 语句中吗?

【问题讨论】:

标签: groovy


【解决方案1】:

使用respondsTo

class Foo {
   String prop
   def bar() { "bar" }
   def bar(String name) { "bar $name" }
}

def f = new Foo()

// Does f have a no-arg bar method
if (f.metaClass.respondsTo(f, "bar")) {
   // do stuff
}
// Does f have a bar method that takes a String param
if (f.metaClass.respondsTo(f, "bar", String)) {
   // do stuff
}

【讨论】:

    【解决方案2】:

    只需在你的类中实现 methodMissing:

    class Foo {
       def methodMissing(String name, args) { return null; }
    }
    

    然后,每次尝试调用不存在的方法时,都会得到一个空值。

    def foo = new Foo();
    assert foo.someMethod(), null
    

    更多信息,请看这里:http://groovy.codehaus.org/Using+methodMissing+and+propertyMissing

    【讨论】:

    • 这意味着他所有没有 someMethod 行为的对象都必须实现该方法?
    【解决方案3】:

    您应该能够执行以下操作:

    SomeObj.metaClass.getMetaMethod("someMethod")
    

    或者您可以回退到旧的 Java 反射 API。

    【讨论】:

      【解决方案4】:

      您可以通过使用getMetaMethod 和安全导航运算符?. 来实现此目的:

      def str = "foo"
      def num = 42
      
      def methodName = "length"
      def args = [] as Object[]
      
      assert 3 == str.metaClass.getMetaMethod(methodName, args)?.invoke(str, args);
      assert null == num.metaClass.getMetaMethod(methodName, args)?.invoke(num, args);
      

      【讨论】:

        【解决方案5】:

        如果类:

           MyClass.metaClass.methods*.name.any{it=='myMethod'}//true if exist
        

        如果对象:

        myObj.class.metaClass.methods*.name.any{it=='myMethod'}//true if exist
        

        【讨论】:

          【解决方案6】:

          您可以使用非常简洁的方式:

          if(someObj.&methodName){
           //it means someObj has the method
          }
          

          【讨论】:

            猜你喜欢
            • 2013-07-27
            • 1970-01-01
            • 1970-01-01
            • 2010-11-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多