1

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.

Community
  • 1
  • 1
SergioL08
  • 121
  • 1
  • 3
  • 12

2 Answers2

2

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:

interface Factory<E> {  
    E newInstance();
}

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.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
1

You don't have access to E at run-time in the way you want. You can hack around this, but it's a bit messy:

protected Class<E> filterClass;

@SuppressWarnings("unchecked")
public MyExpandableListAdapter() {
    filterClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}

After you have the class you can use reflection to create an instance. See this tutorial for more information.

You should consider if the added complexity is worth it.

beerbajay
  • 19,652
  • 6
  • 58
  • 75
  • Thank you very much. I have solved using the solution posted by Andrzej Doyle. I think that I will try also your idea to curiosity :) It is another good solution :) Have a nice day ;) – SergioL08 Feb 27 '12 at 09:41