programming-examples/java/Multi ClassLoader Demo.java
2019-11-18 13:43:20 +01:00

84 lines
2.2 KiB
Java

Multi ClassLoader Demo
import java.net.URLClassLoader;
import java.net.URL;
import java.io.File;
public class MultiCLDemo
{
public static void main(String[] args)
{
if (args.length<3)
{
System.out.println("Usage: java MultiCLDemo "+" ...");
System.out.println("Loads and runs toString() on class_name "+"found in each subDir.");
System.exit(0);
}
try
{
String className = args[0];
int count = args.length-1;
URL tmpURL;
Object[] objects = new Object[count];
URLClassLoader[] loaders = new URLClassLoader[count];
System.out.println("Loading "+count+" different classes "+"named: "+className);
for (int i=0; i {
tmpURL = new File(args[i+1]).toURL();
System.out.println("\nLoading from: "+tmpURL);
loaders[i] = new URLClassLoader(new URL[] { tmpURL });
objects[i] = loaders[i].loadClass(className).newInstance();
for (int k=0; k<=i; k++)
{
System.out.println("Got object: "+objects[k]);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
/*Some sample classes to load...
// c:\a/HelloWorld.java
public class HelloWorld
{
public String toString()
{
return "Hello";
}
}
// c:\b/HelloWorld.java
public class HelloWorld
{
public String toString()
{
return "World";
}
}
// c:\c/HelloWorld.java
public class HelloWorld
{
public String toString()
{
return "Hello World";
}
}
The code running...
java MultiCLDemo HelloWorld a b c
Loading 3 different classes named:
HelloWorldLoading from: file:/.../class_loader_demo/a/Got object:
HelloLoading from: file:/.../class_loader_demo/b/Got object:
HelloGot object: WorldLoading from: file:/.../class_loader_demo/c/Got object:
HelloGot object: WorldGot object: Hello World
regards, btcoburn*/