Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to dynamically load java class files

What would be a good way to dynamically load java class files so that a program compiled into a jar can read all the class files in a directory and use them, and how can one write the files so that they have the necessary package name in relation to the jar?

like image 555
MirroredFate Avatar asked Jun 02 '11 20:06

MirroredFate


People also ask

What is Java dynamic loading?

Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Dynamic class loading is done when the name of the class is not known at compile time.


1 Answers

I believe it's a ClassLoader you're after.

I suggest you start by looking at the example below which loads class files that are not on the class path.

// Create a File object on the root of the directory containing the class file File file = new File("c:\\myclasses\\");  try {     // Convert File to a URL     URL url = file.toURI().toURL();          // file:/c:/myclasses/     URL[] urls = new URL[]{url};      // Create a new class loader with the directory     ClassLoader cl = new URLClassLoader(urls);      // Load in the class; MyClass.class should be located in     // the directory file:/c:/myclasses/com/mycompany     Class cls = cl.loadClass("com.mycompany.MyClass"); } catch (MalformedURLException e) { } catch (ClassNotFoundException e) { } 
like image 87
aioobe Avatar answered Sep 28 '22 13:09

aioobe