In Groovy, a class is a blueprint for creating objects. It defines the properties and behavior of the objects that are created from it. A class is a way of organizing and structuring your code, allowing you to create and use objects that have the same characteristics and behavior. To check if a class has a property in Groovy, you can use the hasProperty()
method. Below are some examples:
Check if Class has Property in Groovy Examples
class MyClass { String property1 String property2 } def myClass = new MyClass() if (myClass.hasProperty("property1")) { println "property1 exists" } else { println "property1 does not exist" } if (myClass.hasProperty("property2")) { println "property2 exists" } else { println "property2 does not exist" }
This code defines a class MyClass
with two properties - property1
and property2
. It then creates an instance of the class and checks if the instance has the properties property1
and property2
using the hasProperty()
method. Since the class has these properties, the code will print "property1 exists
" and "property2 exists
".
Here's another example that shows how to check if a class has a property that does not exist:
class MyClass { String property1 String property2 } def myClass = new MyClass() if (myClass.hasProperty("property1")) { println "property1 exists" } else { println "property1 does not exist" } if (myClass.hasProperty("property3")) { println "property3 exists" } else { println "property3 does not exist" }
In this code, we check if the instance of MyClass
has the property property3
. Since this property does not exist in the class, the code will print "property3 does not exist
".