Showing posts with label property available. Show all posts
Showing posts with label property available. Show all posts

Monday, September 23, 2013

Groovy Check If Method or Property is Available

In Groovy we can easily see if a method or property is available for an object. We can use the respondsTo() and hasProperty() methods to see if the method or property can be invoked or accessed. We can not check for methods or properties which are added by overriding the methodMissing()/propertyMissing() or invokeMethod()/getProperty() methods.
Assume a service: TestService.groovy:

class TestService {
    String someProperty;
    def serviceMethod() {

    }

    def printString(String str) {
        println "String: " + str;
    }

    def printString(String str, Integer count, Integer map) {
        println "String: " + str;
    }
}

Now test if specific method existing:

TestService testService = new TestService();

println testService.metaClass.respondsTo(testService, "noMethodExists") ? "Exists: noMethodExists()" : "Not Exists: noMethodExists()";

println testService.metaClass.respondsTo(testService, "printString", String) ? "Exists: printString()" : "Not Exists: printString()";

ArrayList arrayList = new ArrayList();
arrayList.push(String);
arrayList.push(Integer);
def args = arrayList as Object[];
println (testService.metaClass.respondsTo(testService, "printString", args) ? "Exists: printString(String, Integer)" : "Not Exists: printString(String, Integer)");

arrayList = new ArrayList();
arrayList.push(String);
arrayList.push(Integer);
arrayList.push(Integer);
args = arrayList as Object[];
println (testService.metaClass.respondsTo(testService, "printString", args) ? "Exists: printString(String, Integer, Integer)" : "Not Exists: printString(String, Integer, Integer)");

And output will be as:

Not Exists: noMethodExists()
Exists: printString()
Not Exists: printString(String, Integer)
Exists: printString(String, Integer, Integer)

Now check specific property exists:

TestService testService = new TestService(); 

if(testService.metaClass.hasProperty(testService, "someProperty")) {
    println "Property: someProperty exists";
} else {
    println "Property: someProperty not exists";
} 
 
if(testService.metaClass.hasProperty(testService, "someName")) {
    println "Property: someName exists";
} else {
    println "Property: someName not exists";
}

And output will be as:

Property: someProperty exists
Property: someName not exists