Java examples for Reflection:Constructor
new Instance Any Parameter
import java.lang.reflect.Constructor; public class Main{ public static void main(String[] argv) throws Exception{ Class clazz = String.class; Object[] params = new String[]{"1","abc","level",null,"java2s.com","asdf 123"}; System.out.println(newInstanceAnyParameter(clazz,params)); }//from w w w .j a v a2s . co m public static Object newInstanceAnyParameter(Class clazz, Object[] params) throws DIIException { try { return findConstructorWithParams(clazz, params.length) .newInstance(params); } catch (Exception ex) { throw new DIIException(ex); } } private static Constructor findConstructorWithParams(Class clazz, int paramCount) throws NoSuchMethodException { Constructor[] inits = clazz.getConstructors(); for (int i = 0; i < inits.length; ++i) { if (inits[i].getParameterTypes().length == paramCount) { return inits[i]; } } throw new NoSuchMethodException("constructor for class '" + clazz.getName() + "' with " + paramCount + " parameters"); } }