Using reflection to instantiate a Java class from a .class file

I have a path to a .class file and I want to create it from a running program. I have to "load" this class, but its class path is not in my .jar or my project, it is in a folder besides it (cannot use Class.forName ()). How can I instantiate this class?

+4
source share
1 answer

You can proceed as follows:

File myFolder = new File("myfolder");
URLClassLoader classLoader = new URLClassLoader(new URL[]{myFolder.toURI().toURL()}, Thread.currentThread().getContextClassLoader());
Class<?> myClass = Class.forName("my.package.Myclass", true, classLoader);
Myclass obj = (Myclass)myClass.newInstance();

First, you create an instance URLClassLoaderusing the context Classloaderas the parent, then load the class using this new one, Classloaderand finally create the instance (here it calls the constructor with no arguments).

+4

All Articles