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

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


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

  public static void addFile(File f) throws IOException {
    addURL(f.toURL());
  }
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.setAccessible(true);
method.invoke(sysLoader, new Object[]{u});
} catch (Throwable t) {
t.printStackTrace();
throw new IOException("Error, could not add URL to system classloader");
}
}
public static void main(String[] args) throws IOException
{
	String u="E:\\javadem\\";
	addFile(u);
    Class.forName("B");
	System.out.println(System.getProperty("java.class.path"));
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?
Posted
Updated 21-Jun-21 21:23pm
v2
Comments
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.
   
Comments
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month



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