使用 Java 泛型从类名中获取类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2969712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting type from class name with Java generics
提问by newbie
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 接口/实现......
回答by dplass
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();
}
}
回答by taer
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);
}
}
回答by Powerlord
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?
为您的方法签名?
回答by user268396
And you cannot simply add a constructor parameter?
你不能简单地添加一个构造函数参数?
public abstract class MyClass<T> {
public MyClass(Class<T> type) {
// do something with type?
}
}

