Joseph
Joseph

Reputation: 1463

Groovy respondsTo no argument method

I have an object, MyObject, that I need to check if it contains a method, say format. I need to check if this method signature has no arguments, or if it has an argument of MyType. I don't see a way of checking if a method respondsTo no arguments. I have tried the following:

if(MyObject.metaClass.respondsTo(MyObject.class, "format"))
{ ... }
else if(MyObject.metaClass.respondsTo(MyObject.class, "format", MyType)
{ ... }

The problem is that the first if check always evaluates to true, regardless of how many arguments the actual method signature takes in. It only evaluates to false if the method doesn't exist in any form.

For now what I've done is simply re-arranged the if/else if checks so that the typed check comes before the no argument check. This works, but it isn't all that accurate. Another option it to take the result list from the respondsTo call and evaluate if the resulting Cached Method(s) have an empty argument signature. This would also work, but seems excessive compared to how easy the other signature validation is.

Edit: adding versions Grails 1.3.7 Groovy 1.8

Upvotes: 0

Views: 902

Answers (1)

tim_yates
tim_yates

Reputation: 171084

Try

MyObject.metaClass.respondsTo( MyObject, "format", null )

Or

MyObject.metaClass.respondsTo( MyObject, 'format' ).findAll { it.paramsCount == 0 }

Upvotes: 2

Related Questions