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);
}
编辑:正如评论中所指出的,如果您在参数中传递子类,此代码将不起作用