Getting property class from property name
Recently in one of my project i had a requirement of identifying the class of a property of an object with object class and property name and then determining whether it’s an Enum class or not. I found an easy solution for this using Reflection API. Using Java Reflection you can inspect the fields (member variables) of classes. This is done via the Java class java.lang.reflect.Field and calling geType()
on this Field object gives the class of that property.
[java]
class Utils {
public static def getClass(Class objectClass, String propertyName) {
def propertyClass = null
try {
propertyClass = objectClass.getDeclaredField(propertyName)?.type
}
catch (NoSuchFieldException ex){
log.error("No such property exist in this object class&"+objectClass)
}
return propertyClass
}
}
//Checking enum class or not
Utils.getClass(object.class,"someFieldName")?.isEnum()
[/java]
There is one more benefit. One can also check whether particular property exists in a class or not as getDeclaredField
throws NoSuchFieldException
if there is no such property with given name in the object class.
Regards
$achin verma
sachin.verma@intelligrape.com
Are you serious? Where is groovy? Why cant i do it in one line like:
object.metaclass.declaredFields.findResullt{it.name == “propertyName”?it.type:null)
Or for Class
objectClass.declaredFields.findResult(it.name == “properrtyName”?it.type:null)
Or
To Check Enum:
objectClass.declaredFields.grep{it.isEnum() && it.name==”propertyName”?it.type:null}
ALSO
Having a method named getClass in a Util class seems wrong ethically as it indicates a getter or technically overloaded getter and it seems we are getting the class of the Util class. Where is the context or aspect?
Code seems confusing.