首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

利用classloader生成class的步骤

2013-12-29 
利用classloader生成class的方法1:无参数构造体public static Object create(String className) throws Cl

利用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));    }

热点排行