newbie
newbie

Reputation: 24635

Getting type from class name with Java generics

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 queries should be generally available to all DAO interfaces/implementations...

Upvotes: 2

Views: 17839

Answers (4)

Powerlord
Powerlord

Reputation: 88796

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?

Upvotes: 0

taer
taer

Reputation: 543

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);
    }
}

Upvotes: 4

user268396
user268396

Reputation: 11986

And you cannot simply add a constructor parameter?

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

Upvotes: 0

dplass
dplass

Reputation: 1473

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();
  }
}

Upvotes: 7

Related Questions