Java : How I can get the type of the generic type at runtime

标签 java generics

Possible Duplicates:
Get generic type of class at runtime
How to get the generic type at runtime?

你好,

如何在运行时获取 java 中泛型类型的类型?

在 C# 中,我可以使用 typeof运算符(operator)。随着typeof运算符我得到一个类型对象,其中包含有关运行时此泛型类型的类型的更多信息。

Java中有等价的运算符吗?

提前致谢。

亲切的问候,帕特里克

//编辑:

我想做什么:

public ArrayList<T> SelectObjects() {

            // I need to get here the type name for the oql script! 
    //this.SelectObjects( "select p from " + Class.forName(T));


}

public ArrayList<T> SelectObjects(String oql) {

     try {
            Iterator<T> iterator =
                   this.em.createQuery(oql).getResultList().iterator();

            ArrayList<T> objects = 
                new ArrayList<T>();

            while(iterator.hasNext())
            {
                objects.add(iterator.next());
            }

            return objects;
         }
         catch (Exception e) {
            e.printStackTrace();
            return null;
         }
}

我动态设置了一个 oql 脚本。如何从 T 获取类型?

谢谢!

最佳答案

在对象实例上使用getClass()

public void someMethod(T instance) {

    if ( instance != null ) {
        System.out.println("Instance type: " + instance.getClass();
    }

}

您可以使用反射来获取有关检索到的类的更多信息。

关于Java : How I can get the type of the generic type at runtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5914525/

相关文章:

java - 强制将 a 从父类型解析为子类型?

java - 如何将 DefaultListModel 中的数据追加到 .txt 文件中

ios - Objective-C 泛型-安全数组/字典字面量

Eclipse 调试器错误 : Evaluations must contain either an expression. ..

java - 不兼容的类型 : T#1 cannot be converted to T#2

swift - 对关联类型有约束的通用下标导致 "Cannot subscript a value of type..."

scala - 为什么 scala 无法从 2 个函数推断通配符类型?

java - 方法中只有一个 return 语句,但对象无法实例化。无返回语句错误

java - 在 NIO 中配对 SocketChannel

java - 如何防止类型删除?