Java Generic Classes

Jakob Jenkov
Last update: 2015-07-03

Generic Classes in Java

It is possible to generify your own Java classes. Generics is not restricted to the predefined classes in the Java API's. Here is a simple example:

public class GenericFactory<T> {

    Class theClass = null;

    public GenericFactory(Class theClass) {
        this.theClass = theClass;
    }

    public T createInstance()
    throws IllegalAccessException, InstantiationException {
        return (T) this.theClass.newInstance();
    }
}

The <T> is a type token that signals that this class can have a type set when instantiated. Here is an example of how:

GenericFactory<MyClass> factory =
    new GenericFactory<MyClass>(MyClass.class);

MyClass myClassInstance = factory.createInstance();

Notice how it is not necessary to cast the object returned from the factory.createInstance() method. The compiler can deduct the type of the object from the generic type of the GenericFactory created, because you specified the type inside the <>.

Each instance of the GenericFactory can be generified to different types. Here are two examples:

GenericFactory<MyClass> factory =
    new GenericFactory<MyClass>(MyClass.class);

MyClass myClassInstance = factory.createInstance();


GenericFactory<SomeObject> factory =
    new GenericFactory<SomeObject>(SomeObject.class);

SomeObject someObjectInstance = factory.createInstance();

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















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