0

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

Hi there,

How I can get the type for a generic type in java at runtime?

In C# I can use the typeof operator. With the typeof operator I get a type object with further information about the type of this generic type at runtime.

Is there a equivalent operator in Java?

Thanks in advance.

Kind regards, patrick

//Edit :

What I want to do :

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;
         }
}

I set up an oql script dynamically. How can I get the type from T?

Thanks!

Community
  • 1
  • 1
bitsmuggler
  • 1,689
  • 2
  • 17
  • 30

1 Answers1

1

Use getClass() on the object instance.

public void someMethod(T instance) {

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

}

You can use reflection to obtain more information about the retrieved class.

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
  • Hi JVerstry, Thanks for your answer. But my problem is, that I haven't an instance as parameter. In C# I can do typeof(T) and I get the whole type information. – bitsmuggler May 07 '11 at 06:39
  • In this case, there is NO other option but to pass a Class parameters in your function and obtain type information from it. – Jérôme Verstrynge May 07 '11 at 12:55