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&g开发者_JAVA百科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...
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();
}
}
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);
}
}
And you cannot simply add a constructor parameter?
public abstract class MyClass<T> {
public MyClass(Class<T> type) {
// do something with type?
}
}
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?
精彩评论