To do this, you need a special class loader, and in this class loader you need to override the findClass(String name) method
Example:
public class CustomClassLoader extends ClassLoader { final String basePath = "/your/base/path/to/directory/named/repository/"; @Override protected Class<?> findClass(final String name) throws ClassNotFoundException { String fullName = name.replace('.', '/'); fullName += ".class"; String path = basePath + fullName ; try { FileInputStream fis = new FileInputStream(path); byte[] data = new byte[fis.available()]; fis.read(data); Class<?> res = defineClass(name, data, 0, data.length); fis.close(); return res; } catch(Exception e) { return super.findClass(name); } } }
Then you will load the classes from a custom location. For instance:
Class<?> clazz = Class.forName("my.pretty.Clazz", true, new CustomClassLoader()); Object obj = clazz.newInstance();
By doing this, you tell the JVM that a class named my.pretty.Clazz must be loaded by your custom classloader, which knows how and where from to load its own class. It resolves the fully qualified class name (for example, my.pretty.Clazz ) to the file name (in our case: /your/base/path/to/directory/named/repository/my/pretty/Clazz.class ), then loads the resulting resource into as a byte array and finally converts this array into an instance of Class .
This example is very simple and demonstrates the general method of loading custom classes, as in your case. I suggest you read some articles about loading classes, like this one .
source share