Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create generic type?

Tags:

java

generics

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?

like image 709
Erik Z Avatar asked Feb 03 '14 06:02

Erik Z


2 Answers

You can't use implements here.

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

So you can use Abstract Class there

<T extends MyAbstractClass>
like image 175
Ruchira Gayan Ranaweera Avatar answered Oct 01 '22 03:10

Ruchira Gayan Ranaweera


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.

like image 43
aljipa Avatar answered Oct 01 '22 05:10

aljipa