1

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........

3 Answers 3

3

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.
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

The import is not needed, you aren't using anything from there. All you need is one method: Class.newInstance().
1

If you want manage parameters, you can do that :

public static <T> T instantiate(Class<T> clazz, Object ... parameters) throws Exception {
    Validate.notNull(clazz, "Argument 'clazz' null!");
    if (!ArrayUtils.isEmpty(parameters)) {
        Class<?> [] parametersType = new Class<?>[parameters.length];
        for(int i=0 ; i<parameters.length ; i++) {
            parametersType[i] = parameters[i].getClass();
        }
        return clazz.getConstructor(parametersType).newInstance(parameters);
    }
    return clazz.newInstance();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.