【问题标题】:Java : How I can get the type of the generic type at runtime [duplicate]Java:如何在运行时获取泛型类型的类型 [重复]
【发布时间】:2011-05-07 14:41:36
【问题描述】:

可能的重复:
Get generic type of class at runtime
How to get the generic type at runtime?

你好,

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

在 C# 中,我可以使用 typeof 运算符。使用 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 中获取类型?

谢谢!

【问题讨论】:

    标签: java generics


    【解决方案1】:

    在对象实例上使用getClass()

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

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

    【讨论】:

    • 您好 JVerstry,感谢您的回答。但我的问题是,我没有一个实例作为参数。在 C# 中,我可以执行 typeof(T) 并获得整个类型信息。
    • 在这种情况下,除了在函数中传递 Class 参数并从中获取类型信息之外,别无选择。
    猜你喜欢
    • 2016-04-19
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 2015-11-20
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多