tags:

views:

97

answers:

4

I have following Class, I need to get type in constructor, how can I do that?

public abstract class MyClass<T> {

    public MyClass()
    {
        // I need T type here ...
    }

}

EDIT:

Here is concrete example what I want to achieve:

public abstract class Dao<T> {

    public void save(GoogleAppEngineEntity entity)
    {
        // save entity to datastore here
    }

    public GoogleAppEngineEntity getEntityById(Long id)
    {
        // return entity of class T, how can I do that ??
    }

}

What I want to do is to have this class extended to all other DAOs, because other DAOs have some queries that are specific to those daos and cannot be general, but these simple quries should be generally available to all DAO interfaces/implementations...

+1  A: 

You can get it, to some degree... not sure if this is useful:

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

abstract class MyClass<T> {
  public MyClass() {        
    Type genericSuperclass = this.getClass().getGenericSuperclass();
    if (genericSuperclass instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) genericSuperclass;
      Type type = pt.getActualTypeArguments()[0];
      System.out.println(type); // prints class java.lang.String for FooClass
    }
  }
}

public class FooClass extends MyClass<String> { 
  public FooClass() {
    super();
  }
  public static void main(String[] args) {
    new FooClass();
  }
}
dplass
Note that if you did `new ConcreteMyClass<String>()`, where `public class ConcreteMyClass<T> extends MyClass<T>` you would just get "T", since the type isn't reified.
Mark Peters
Dao<T extends GoogleAppEngineEntity> might do the trick.
dplass
A: 

And you cannot simply add a constructor parameter?

public abstract class MyClass<T> { 
  public MyClass(Class<T> type) {
    // do something with type?
  }
}
A: 

We've done this

public abstract BaseClass<T>{
protected Class<? extends T> clazz;

    public BaseClass(Class<? extends T> theClass)
    {
        this.clazz = theClass;
    }
...
}

And in the subclasses,

public class SubClass extends BaseClass<Foo>{
    public SubClass(){
       super(Foo.class);
    }
}
taer
A: 

If I'm not reading this wrong, wouldn't you just want

public <T> void save(T entity)

and

public <T> T getEntityById(Long id)

for your method signatures?

R. Bemrose