Getting property class from property name

26 / Sep / 2012 by Sachin Verma 1 comments

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

FOUND THIS USEFUL? SHARE IT

comments (1 “Getting property class from property name”)

  1. Jason John

    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.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *