Erik Z
Erik Z

Reputation: 4780

How to create generic type?

I've defined a class like this:

public class MyClass<T implements MyInterface> {
    public T getMy() {
        return new T();
    }
}

This won't compile. I'm not allowed to create the generic type T.

How can I solve this? Is there any good patterns to do this? Can I solve this by using an abstract class instead of the interface? Do I have to use reflection?

Upvotes: 5

Views: 99

Answers (4)

Makoto
Makoto

Reputation: 106508

There's a few issues here.

  • Your syntax for creating a bounded generic type is incorrect; you need to use the extends keyword. The extends keyword is more general in this sense, since it's used to mean that the generic type could either extend another class, or implement an interface.

  • You can't instantiate a generic type directly. Here's a clunkier way (without reflection, as it were), which was provided by this Stack Overflow answer:

    public T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
        return clazz.newInstance();
    }
    

Upvotes: 0

stinepike
stinepike

Reputation: 54742

public class MyClass<T extends MyInterface> {

   T getMy(Class<T> clazz) throws InstantiationException, IllegalAccessException
    {
        return clazz.newInstance();
    }
}

Upvotes: 1

clumsy
clumsy

Reputation: 716

You can achieve this by passing an actual class type (e.g. to the constructor), Class<T> and calling newInstance() on it if default constructor is OK with you. If you need another constructor you would need to use reflection API, e.g. via getDeclaredConstructors() on this very class type object.

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35587

You can't use implements here.

<T implements MyInterface> // can't use interface.

So you can use Abstract Class there

<T extends MyAbstractClass>

Upvotes: 3

Related Questions