利用反射创建对象

    /*
     * 通过反射创建带参数的对象
     */
    public Object Creatobject(String ClassPath, Object[] Params) throws Exception {
        Class demo = null;
        Object obj = null;
        demo = Class.forName(ClassPath);
        if (Params != null) {
            Class[] argsClass = new Class[Params.length];
            for (int i = 0, j = Params.length; i < j; i++) {
                argsClass[i] = Params[i].getClass();
            }
            Constructor cons = demo.getConstructor(argsClass);
            obj = cons.newInstance(Params);
        } else {
            obj = demo.newInstance();
        }
        return obj;
    }

说明: ClassPath为“包名.类名”的方式,如“java.lang.String”;

你可能感兴趣的:(Java)