tags:

views:

72

answers:

2

I have a method

 public static <T> T createObject(Class<T> t){

 }

You see, I want to get a instance of T.

I know this can be realized, because:

 public <T> T find(Object id, Class<T> type) {
  return (T) this.em.find(type, id);
 }

Help me........

+2  A: 

siunds like you need reflection

import java.reflect.*;
...
Class klass = obj.class;
Object newObj = klass.newInstance();
return (T)newObj;

note: written from memory, so the api may be slightly different.

atk
The import is not needed, you aren't using anything from there. All you need is one method: Class.newInstance().
Mike Baranczak
+3  A: 

If the class t has a no-args constructor, then the Class.newInstance() method will do what is needed:

 public static <T> T createObject(Class<T> t) 
 throws InstantiationException, IllegalAccessException {
    return t.newInstance();
 }

Note that you have to either propagate or deal with checked exceptions arising from things like:

  • the t object represents an interface or an abstract class,
  • the t class doesn't have a no-args constructor, or
  • the t class or its no-args constructor are not accessible.
Stephen C