读书人

利用classloader生成class的步骤

发布时间: 2013-12-29 13:07:03 作者: rapoo

利用classloader生成class的方法
1:无参数构造体

public static Object create(String className) throws ClassLoadException {        Object object = null;        Thread t = Thread.currentThread();        ClassLoader cl = t.getContextClassLoader();        try {            object = cl.loadClass(className).newInstance();        } catch (InstantiationException e) {            throw new ClassLoadException(e);        } catch (IllegalAccessException e) {            throw new ClassLoadException(e);        } catch (ClassNotFoundException e) {            throw new ClassLoadException(e);        }        return object;    }

2:有参数的构造方法
public static Object create(String className,                                 Object[] constructorParameter)                                 throws ClassLoadException {        Constructor[] constructors = null;        Thread t = Thread.currentThread();        ClassLoader cl = t.getContextClassLoader();        try {            constructors = cl.loadClass(className).getConstructors();        } catch (SecurityException e) {            throw new ClassLoadException(e);        } catch (ClassNotFoundException e) {            throw new ClassLoadException(e);        }        for (int i = 0; i < constructors.length; i++) {            Object object = null;            try {             object = constructors[i].newInstance(constructorParameter);            } catch (IllegalArgumentException e) {                continue;            } catch (InstantiationException e) {                throw new ClassLoadException(e);            } catch (IllegalAccessException e) {                throw new ClassLoadException(e);            } catch (InvocationTargetException e) {                throw new ClassLoadException(e);            }              if (object != null) {                return object;            }        }        throw new ClassLoadException(            new IllegalArgumentException("class name is " + className));    }

读书人网 >编程

热点推荐