简体   繁体   English

如何通过课程获取实例?

[英]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. 你看,我想得到一个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: 如果类t具有无参数构造函数,则Class.newInstance()方法将执行所需的操作:

 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, t对象表示接口或抽象类,
  • the t class doesn't have a no-args constructor, or t类没有无参数构造函数,或者
  • the t class or its no-args constructor are not accessible. t类或其no-args构造函数不可访问。

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. 注意:是从内存写入的,因此api可能会略有不同。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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