class MyClass {
public MyClass(Long l, String s, int i) {
}
}
你需要像这样表明你打算使用这个构造函数:
Class classToLoad = MyClass.class;
Class[] cArg = new Class[3]; //Our constructor has 3 arguments
cArg[0] = Long.class; //First argument is of *object* type Long
cArg[1] = String.class; //Second argument is of *object* type String
cArg[2] = int.class; //Third argument is of *primitive* type int
Long l = new Long(88);
String s = "text";
int i = 5;
classToLoad.getDeclaredConstructor(cArg).newInstance(l, s, i);
final Constructor constructor = clazz.getConstructors()[0];
final int constructorArgsCount = constructor.getParameterCount();
if (constructorArgsCount > 0) {
final Object[] constructorArgs = new Object[constructorArgsCount];
int i = 0;
for (Class parameterClass : constructor.getParameterTypes()) {
Object dummyParameterValue = getDummyValue(Class.forName(parameterClass.getTypeName()), null);
constructorArgs[i++] = dummyParameterValue;
}
instance = constructor.newInstance(constructorArgs);
} else {
instance = clazz.newInstance();
}
这就是getDummyValue()方法的样子,
private static Object getDummyValue(final Class clazz, final Field field) throws Exception {
if (int.class.equals(clazz) || Integer.class.equals(clazz)) {
return DUMMY_INT;
} else if (String.class.equals(clazz)) {
return DUMMY_STRING;
} else if (boolean.class.equals(clazz) || Boolean.class.equals(clazz)) {
return DUMMY_BOOL;
} else if (List.class.equals(clazz)) {
Class fieldClassGeneric = Class.forName(((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0].getTypeName());
return List.of(getDummyValue(fieldClassGeneric, null));
} else if (USER_DEFINED_CLASSES.contains(clazz.getSimpleName())) {
return createClassInstance(clazz);
} else {
throw new Exception("Dummy value for class type not defined - " + clazz.getName();
}
}