Click here to Skip to main content
15,917,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: is in C directory and is in D directory. I am trying to load B.class in runtime using the following code:

import java.lang.reflect.Method;
import java.util.*;

class A
private static final Class[] parameters = new Class[]{URL.class};
public static void addFile(String s) throws IOException {
    File f = new File(s);
  }//end method

  public static void addFile(File f) throws IOException {
public static void addURL(URL u) throws IOException {

URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL",parameters);
method.invoke(sysLoader, new Object[]{u});
} catch (Throwable t) {
throw new IOException("Error, could not add URL to system classloader");
public static void main(String[] args) throws IOException
	String u="E:\\javadem\\";
B obj=new B(); //here, it shows the error.


What I have tried:

Now, it loads the class. The problem is I cannot access the class. If I try to create a object for that class, it shows the following error:

B cannot be resolved to a type

How can I access that class file?
Updated 21-Jun-21 20:23pm
Richard MacCutchan 22-Jun-21 3:39am    
You cannot create an instance of a class that has not been compiled in your source program. You are using reflection to get the class so you must use reflection to create instances and access the object's methods.
15160877 22-Jun-21 5:45am    
It worked. Thank you

1 solution

You already asked this question at Why it is not working[^]. And we explained why you cannot do it.
Share this answer
15160877 18-Jun-21 4:07am    
My previous question was about setting the path using setProperty(). I can't set it using SetProperty() method. But, I read that I can create an custom dynamic class loader and pass the classpath. Even, this will not work? Then, how do we add a class or jar file at runtime?
Richard MacCutchan 18-Jun-21 6:04am    
See the first link in the Google search results at custom dynamic class loader - Google Search[^].

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900