如何在每次创建实例时从CustomClassLoader中的磁盘重新加载.class文件

时间:2015-01-31 06:44:36

标签: java reflection classloader urlclassloader

我创建了一个CustomClassLoader,它继承自ClassLoader以覆盖loadClass方法。

以下是新的CustomClassLoaded

    public class DesignFactoryClassLoader extends ClassLoader{

        public DesignFactoryClassLoader(ClassLoader parent) {
            super(parent);
        }

        public String classCanonicalName= null;

        public Class loadClass(String canonicalName) throws ClassNotFoundException {
             if(!this.classCanonicalName.equals(canonicalName))
                    return super.loadClass(canonicalName);
            try {                   

                    URL classLoadUrl = new URL(this.reloadClassUrl);
                    URLConnection connection = classLoadUrl.openConnection();
                     InputStream input = connection.getInputStream();
                     ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                     int data = input.read();
                    int data = input.read();

                    while(data != -1){
                        buffer.write(data);
                        data = input.read();
                    }
                    input.close();
                    byte[] classData = buffer.toByteArray();

                    return defineClass(canonicalName,
                            classData, 0, classData.length);
                } catch (Exception e) {
                    //TODO Auto-generated catch block
                    e.printStackTrace();
                }
            return null;
          }
}

要从磁盘重新加载特定类,我就是这样做的

ClassLoader parentClassLoader = DesignFactory.class.getClassLoader();
DesignFactoryClassLoader designFactoryClassLoader = new DesignFactoryClassLoader(parentClassLoader);
designFactoryClassLoader.classCanonicalName = classCanonicalName;
Class reloadedCls = designFactoryClassLoader.loadClass(classCanonicalName);
  

我现在遇到的问题是:当MyClass.class被修改后我需要创建一个MyClass实例时,我使用CustomClassLoader创建它,并且.class文件已经加载到customClassLoader中。第二次我需要创建一个实例,我将使用我的逻辑从磁盘重新加载.class文件。我怎么能避免这个?

0 个答案:

没有答案