title: Dynamically load a class and its object in java
body: <p>I have a class file and a saved object of that class. My java application doesn't have that class in its libraries. When I tried to load the object using <a href="https://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html" rel="nofollow">ObjectInputStream</a>, it gives an <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/ClassNotFoundException.html" rel="nofollow">ClassNotFoundException</a>.</p>
  
  <p>Then I use the following code.</p>
  
  <pre><code> URLClassLoader classLoader = new URLClassLoader(new URL[]{classFile.getParentFile().toURI().toURL()});
   classLoader.loadClass(classFile.getName().replace(".class", "")).newInstance();
   myClass= (MyClass) FileIOManager.readObject(classObj);
  </code></pre>
  
  <p>But this code also gives me the same exception when reading the object. Hope for a help to do my task..</p>
  
  <p><strong>MyClass</strong> doesn't have a package name.</p>
  
  <p><strong>FileIOManager.readObject()</strong> is a method I created to read a object and it works fine for other object which have classes inside my libraries.</p>