ClassUtils { public static <T> T newInstanceWithArgs(Class<T> clazz, Class<?>[] argTypes, Object[] args) throws SofaRpcRuntimeException { if (CommonUtils.isEmpty(argTypes)) { return newInstance(clazz); } try { if (!(clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers()))) { Constructor<T> constructor = clazz.getDeclaredConstructor(argTypes); constructor.setAccessible(true); return constructor.newInstance(args); } else { Constructor<T>[] constructors = (Constructor<T>[]) clazz.getDeclaredConstructors(); if (constructors == null || constructors.length == 0) { throw new SofaRpcRuntimeException("The " + clazz.getCanonicalName() + " has no constructor with argTypes :" + Arrays.toString(argTypes)); } Constructor<T> constructor = null; for (Constructor<T> c : constructors) { Class[] ps = c.getParameterTypes(); if (ps.length == argTypes.length + 1) { boolean allMath = true; for (int i = 1; i < ps.length; i++) { if (ps[i] != argTypes[i - 1]) { allMath = false; break; } } if (allMath) { constructor = c; break; } } } if (constructor == null) { throw new SofaRpcRuntimeException("The " + clazz.getCanonicalName() + " has no constructor with argTypes :" + Arrays.toString(argTypes)); } else { constructor.setAccessible(true); Object[] newArgs = new Object[args.length + 1]; System.arraycopy(args, 0, newArgs, 1, args.length); return constructor.newInstance(newArgs); } } } catch (SofaRpcRuntimeException e) { throw e; } catch (Throwable e) { throw new SofaRpcRuntimeException(e.getMessage(), e); } }  static Class forName(String className); static Class forName(String className, boolean initialize); static Class forName(String className, ClassLoader cl); static List<Method> getAllMethods(Class clazz); static List<Field> getAllFields(Class clazz); static T newInstance(Class<T> clazz); static T newInstanceWithArgs(Class<T> clazz, Class<?>[] argTypes, Object[] args); static Object getDefaultPrimitiveValue(Class clazz); static T getDefaultWrapperValue(Class<T> clazz); static String getMethodKey(String interfaceName, String methodName); static boolean isAssignableFrom(Class<?> interfaceClass, Class<?> implementClass);  }
@Test public void testNewInstanceWithArgs() throws Exception { Assert.assertNotNull(ClassUtils.newInstanceWithArgs(TestMemberClass3.class, null, null)); Assert.assertNotNull(ClassUtils.newInstanceWithArgs(TestMemberClass3.class, new Class[] { String.class }, new Object[] { "2222" })); Assert.assertNotNull(ClassUtils.newInstanceWithArgs(TestMemberClass6.class, null, null)); Assert.assertNotNull(ClassUtils.newInstanceWithArgs(TestMemberClass6.class, new Class[] { int.class }, new Object[] { 222 })); Assert.assertNotNull(ClassUtils.newInstanceWithArgs(TestClass3.class, null, null)); Assert.assertNotNull(ClassUtils.newInstanceWithArgs(TestClass3.class, new Class[] { String.class, int.class }, new Object[] { "xxx", 222 })); }