Thursday, October 28, 2010

Class Objects as Type Literals

Class objects can be used as type specifications too, at runtime. For instance, you can create a generified method like this:

public static <T> T getInstance(Class<T> theClass)
throws IllegalAccessException, InstantiationException {

return theClass.newInstance();

Here are a few examples of calls to the getInstance() method:

String string   = getInstance(String.class);

MyClass myClass = getInstance(MyClass.class);

As you can see the return type changes depending on what class object you pass in as parameter to the method. This can be quite handy in database API's like Butterfly Persistence where you read objects from a database. Here is an example method definition:

public static <T> T read(Class<T> theClass, String sql)
throws IllegalAccessException, InstantiationException {

//execute SQL.

T o = theClass.newInstance();
//set properties via reflection.

return o;

Here is how you would call the read() method:

Driver employee   = read(Driver.class, "select * from drivers where id=1");

Vehicle vehicle = read(Vehicle.class, "select * from vehicles where id=1");

No comments:

Post a Comment