I'm trying to write a code that loads classes dynamically at run time
public class URLDynClassLoader {
public URLDynClassLoader(){
try{
loadclasses( new File("C:/Users/Miller/Desktop/test/") , "Shapes." );
}
catch(ClassNotFoundException e){
e.printStackTrace();
System.out.println(e.getMessage());
}
catch( Exception f ){
System.out.println(f.getMessage());
System.out.println("error");
}
}
private ArrayList<String> getClassNames( File folder ){
File[] listOfFiles = folder.listFiles();
ArrayList<String> fileNames = new ArrayList<String>() ;
for (File file : listOfFiles) {
if (file.isFile()) {
if( accept(file.getName()) ){
fileNames.add(file.getName());
}
}
}
return fileNames ;
}
ArrayList<Class> loadclasses( File folder , String packageName ) throws MalformedURLException, ClassNotFoundException{
URLClassLoader load = URLClassLoader.newInstance( new URL[] { folder.toURL() }) ;
ArrayList<Class> data = new ArrayList<Class>();
ArrayList<String> names = getClassNames(folder);
for(int i=0 ; i<names.size() ; ++i){;
data.add(load.loadClass( fixName( packageName , names.get(i) ) ));
System.out.println("i"+i);
}
return data ;
}
private String fixName(String packageName, String className ) {
className = className.replaceAll(".class", "");
return packageName+className;
}
public boolean accept(String arg) {
return arg.endsWith(".class");
}
public static void main(String[] args) {
new URLDynClassLoader();
}
}
the problem is that this keeps giving me classNotFound exception , tho i'm pretty sure files .class exist in that directory , another thing I've tried loading already loaded classes and it worked , so it doesn't work only if my code doesn't have the class file !!