集册 Java实例教程 新实例的任何参数

新实例的任何参数

欢马劈雪     最近更新时间:2020-01-02 10:19:05

559
新实例的任何参数


import java.lang.reflect.Constructor;
/**
 * NowJava.com 提 供 
**/


public class Main{

    public static void main(String[] argv) throws Exception{

        Class clazz = String.class;

        Object[] params = new String[]{"1","abc","level",null,"nowjava.com","asdf 123"};

        System.out.println(newInstanceAnyParameter(clazz,params));

    }

    public static Object newInstanceAnyParameter(Class clazz,

            Object[] params) throws DIIException {

        try {

            return findConstructorWithParams(clazz, params.length)/** NowJava.com 提供 **/

                    .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) {

                
展开阅读全文