I want to access a class from another project using ClassLoader. How can I indicate the path to this class and get this class file?
I want to be able to do this with code, as I upload many different class files through my application, and the path for different classes will constantly change.
I use CustomClassLoader, which loads class files, but only if they are in a project and not in another project
import java.io.FileInputStream; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedExceptionAction; public class CustomClassLoader extends ClassLoader { String repoLocation = "C:/TempBINfolder/bin/"; public CustomClassLoader() { } public CustomClassLoader(ClassLoader parent) { super(parent); } @Override protected Class<?> findClass(final String name) throws ClassNotFoundException { AccessControlContext acc = AccessController.getContext(); try { return (Class) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws ClassNotFoundException { FileInputStream fi = null; try { String path = name.replace('.', '/'); fi = new FileInputStream(repoLocation + path + ".class"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[8192];
Class call
for (Class singleClass : listOfClasses) { try { ClassLoader classLoader = new CustomClassLoader(ClassLoader.getSystemClassLoader()); Class stringClass = null; try { stringClass = classLoader.loadClass(singleClass.getName()); } catch (ClassNotFoundException ex) { Logger.getLogger(CompilerForm.class.getName()).log(Level.SEVERE, null, ex); } try { stringClass.newInstance(); } catch (InstantiationException ex) { Logger.getLogger(CompilerForm.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(CompilerForm.class.getName()).log(Level.SEVERE, null, ex); } Class cls = Class.forName(stringClass.getName());
If I try to do Class cls = Class.forName(stringClass.getPackage()+"."+stringClass.getName()); the package will be null
EDIT: the following worked for me
URL classUrl; classUrl = new URL("file:///"+ccl.getRepoLocation()); //This is location of .class file URL[] classUrls = {classUrl}; URLClassLoader ucl = new URLClassLoader(classUrls); Class cls = ucl.loadClass(stringClass.getName()); // Current .class files name
source share