user3111525
user3111525

Reputation: 5203

How to specify a generic class?

I want to generify a class instantiation in the following code:

Old code:

public abstract class Test{
    public static Test instantiate(Class clazz)throws Exception{ //instance of clazz extends Test
        return (Test)clazz.newInstance();
    }
}

Because any instance of parameter clazz would be extending class Test, I would like to achieve something like this:

public static T <T extends Test> instantiate(Class<? extends Test> clazz){
    return clazz.newInstance();
}

It is giving the following compile error:

Unspecified Bound

How to do it using java generics?

Upvotes: 0

Views: 80

Answers (2)

Keppil
Keppil

Reputation: 46209

You have mixed up the order. This is the correct syntax:

public static <T extends Test> T instantiate(Class<T> clazz) {
    return clazz.newInstance();
}

Note that Class<? extends Test> has been changed to Class<T>. You also need to take care of any possible exceptions of course.

Upvotes: 6

Harmlezz
Harmlezz

Reputation: 8068

Try this code:

public static <T extends Test> T instantiate(Class<T> clazz)
throws InstantiationException, IllegalAccessException {
    return clazz.newInstance();
}

Upvotes: 1

Related Questions