4

假设我有一个函数,其目的是创建任何指定类的新实例,然后返回它。也许是这样的:

public static <T> Class<T> forgeClass(Class<T> classReference) {

    return new classReference.getClass();

}

用法(带Employee类):

Employee foo = forgeClass(Employee.class); // new Employee instance

我怎样才能做到这一点?

4

4 回答 4

4

关键是用Class.newInstance

public static <T> T forge(final Class<T> type)
    throws InstantiationException, IllegalAccessException {
  return type.newInstance();
}

使用如下...

final Employee employee = forge(Employee.class);

如果您想使用更复杂的初始化例程,例如Employee(String name),您应该使用Class.getConstructor, 后跟Constructor.newInstance.

final Constructor ctor = Employee.class.getConstructor(String.class);
final Employee employee = ctor.newInstance("Steve");
于 2012-09-09T18:28:22.483 回答
2

您可以使用Class.newInstance()method 并且您的方法的返回类型应该是T而不是Class<T>.

public static <T> T forgeClass(Class<T> classReference) throws InstantiationException, IllegalAccessException {
    return classReference.newInstance();
}
于 2012-09-09T18:29:48.600 回答
1

只需使用newInstance()

Class<?> yourClass;
return yourClass.newInstance();
于 2012-09-09T18:28:51.777 回答
0

Class.newInstance()正是您所需要的:

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

如果要将参数传递给构造函数,则必须使用java.lang.reflect.Constructor<T>

public static <T> T forgeClass(Class<T> classReference, Object... constructorArguments)
        throws InstantiationException, IllegalAccessException, SecurityException,
        NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
    Class<?>[] argumentTypes = new Class<?>[constructorArguments.length];
    for (int i = 0; i < constructorArguments.length; i++)
        argumentTypes[i] = constructorArguments[i].getClass();
    Constructor<T> ctor = classReference.getConstructor(argumentTypes);
    return ctor.newInstance(constructorArguments);
}

编辑:正如评论中所指出的,如果您在参数中传递子类,此代码将不起作用

于 2012-09-09T18:32:15.370 回答