简体   繁体   English

从Java中的泛型类获取类实例

[英]Getting class instance from generic type in Java

I've a method in which I'm passing a generic argument. 我有一个方法,我传递一个泛型参数。 To execute one required method I need the class instance of the same. 要执行一个必需的方法,我需要相同的类实例。 How can I get it. 我怎么才能得到它。 There is a workaround which I'm using but I want to know how can we get the Class instance. 我正在使用一种解决方法,但我想知道如何获取Class实例。

The snippet I'm using is: 我正在使用的片段是:

public <T> T readModelWithId(Class<T> c, Serializable pk) {
    // Some code here.
    T t = (T)session.get(c, pk);
    // Some code here.
    return t;
}

The problem is that I don't want to pass the Class instance in this method as it is same as the return type T which is of generic type. 问题是我不想在这个方法中传递Class实例,因为它与泛型类型的返回类型T相同。

There's no way you can get to something like T.class within that method, so you must pass the class argument since you need it to get your model object from the session. 你无法在该方法中获得类似T.class东西,所以你必须传递类参数,因为你需要它来从会话中获取模型对象。

Moreover, this adds a bit of extra "type-safety". 而且,这增加了一些额外的“类型安全性”。 You will force the caller to specify the return type as an argument, so the returned type will not just be "anything a caller may expect" (although I agree this makes it redundant). 您将强制调用者将返回类型指定为参数,因此返回的类型不仅仅是“调用者可能期望的任何内容”(尽管我同意这会使其变得多余)。

You can't do it because Java implements Generics using "type erasure". 你不能这样做是因为Java使用“类型擦除”来实现泛型。

http://docs.oracle.com/javase/tutorial/java/generics/erasure.html http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

Looks like you are doing a generic DAO. 看起来你正在做一个通用的DAO。 I've done something similar here: 我在这里做了类似的事情:

http://www.matthews-grout.co.uk/2012/01/my-generic-hibernate-dao.html http://www.matthews-grout.co.uk/2012/01/my-generic-hibernate-dao.html

You cannot do anything with generics that you could not do with non-generics with casts. 对于使用非转换的非泛型,你无法对泛型做任何事情。 Consider the non-generic version of your code: 考虑代码的非泛型版本:

public Object readModelWithId(Class c, Serializable pk) {
    // Some code here.
    Object t = session.get(c, pk);
    // Some code here.
    return t;
}

Now ask the same question, can you get rid of the class instance argument c ? 现在问同样的问题,你能摆脱类实例参数c吗?

Generics are more for compile time type safety - you need class instance so compiler does not complain about missing cast. 泛型更适用于编译时类型安全 - 您需要类实例,因此编译器不会抱怨缺少强制转换。 Alternatively you can ditch generics altogether and cast result 或者你可以完全抛弃泛型并投射结果

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

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