简体   繁体   English

使用Java泛型从类名获取类型

[英]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... 我想要做的是将此类扩展到所有其他DAO,因为其他DAO有一些特定于那些daos的查询并且不能是通用的,但这些简单查询通常应该可用于所有DAO接口/实现......

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? 为您的方法签名?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM