Java Generics - Class Objects as Type Literals

Jakob Jenkov
Last update: 2014-06-23

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");

Smart, right?

Jakob Jenkov

Featured Videos

Java ForkJoinPool

P2P Networks Introduction




















Advertisements

High-Performance
Java Persistence
Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next