Possible Duplicate:
Instantiating a generic class in Java
I am studying Generics Java because I would like to implement this:
I have 2 classes that use 1 common class, and in this common class I want to create an Object of a generic class. Here there is a piece of my code so It will be simplest.
//MyFirstClass.java
class MyFirstClass{
...
MyExpandableListAdapter<FirstFilter> mAdapter = new MyExpandableListAdapter<FirstFilter>();
...
}
//MySecondClass.java
class MySecondClass{
...
MyExpandableListAdapter<SecondFilter> mAdapter = new MyExpandableListAdapter<SecondFilter>();
...
}
//common class MyExpandableListAdapter.java
public class MyExpandableListAdapter<E extends Filter> extends BaseExpandableListAdapter implements Filterable {
private E filter;
...
public Filter getFilter(){
if (filter== null)
filter = new <E>(); // Here I want to create an Object, but I get an error on <E>
return filter;
}
}
Is it possible to do it? How I could do it?
Please, help me. Thank you very much.
Due to the way in which generic is implemented, it’s completely impossible to instantiate a generic parameter as you’re trying to do here.
The usual alternative is to use some sort of factory, i.e. a class that implements an interface similar to:
This way, you’d have different implementations of the factory for different versions of
E, and the compiler would check that you’re passing in one of the correct type.