title: Reload class file in tomcat
body: <p>I am creating a class file at run time.</p>
  
  <p>I want to replace the existing class file with the updated one in the class loader.</p>
  
  <p>It is similar to hot swapping (e.g. JRebel) which avoids server restart and redeployment.</p>
  
  <p>I found context.xml approach for tomcat for context reloading.
  But it is not very useful in case of production environment.</p>
  
  <p>Can we register class with ClassLoader at runtime?
  Please suggest if any alternative is there to reload class at runtime.</p>
  
  <hr>
  
  <p>I am using following code to retrieve current classLoader.</p>
  
  <pre><code>ClassLoader classLoader = LoggingAspect.class.getClassLoader();
  </code></pre>
  
  <p>Below is the implementation of load class method.</p>
  
  <pre><code>public class AspectClassLoader extends ClassLoader{
  
  @Override
  public synchronized Class&lt;?&gt; loadClass(String name) throws ClassNotFoundException
  {
      String customLoadClass = "com.log.LoggingAspect";
      try
      {
          if(!customLoadClass.equals(name))
          {
              return super.loadClass(name);
          }
          else
          {
              URL classLoadUrl = new URL(this.reloadClassUrl);
              URLConnection connection = classLoadUrl.openConnection();
              InputStream input = connection.getInputStream();
              ByteArrayOutputStream buffer = new ByteArrayOutputStream();
              int data = input.read();
  
              while(data != -1){
                  buffer.write(data);
                  data = input.read();
              }
  
              input.close();
  
              byte[] classData = buffer.toByteArray();
              return defineClass(name, classData, 0, classData.length);
          }
      }
      catch(Exception e)
      {
          e.printStackTrace();
      }
      return null; 
  }
  </code></pre>
  
  <p>To reload class i am using following code.</p>
  
  <pre><code>AspectClassLoader urlClsLoader = new AspectClassLoader(classLoader);
  Class aspect = urlClsLoader.reloadClass("com.log.LoggingAspect", true, new String("file:"+className));
  </code></pre>
  
  <p>My reload method of the classloader is </p>
  
  <pre><code>public synchronized Class&lt;?&gt; reloadClass(String name, boolean resolve, String reloadClassUrl) throws ClassNotFoundException
  {
      this.reloadClassUrl = reloadClassUrl;
      return this.loadClass(name, resolve);
  }
  </code></pre>
  
  <p>After reloading if i create the new instance of LoggingAspect it still gives me the old instance. Please suggest.</p>
  
  <pre><code>Class aspect = urlClsLoader.reloadClass("com.log.LoggingAspect", true, new String("file:"+className));
          com.log.aspect.Aspect aspectObj = (com.log.aspect.Aspect)aspect.newInstance();
  </code></pre>
  
  <p>Still I am getting the old instance.</p>
  
  <p>Please suggest why classloader does not load the modified class?</p>