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