简体   繁体   中英

How I can get a instance by a class?

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM