简体   繁体   中英

URLClassLoader ClassNotFoundException

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();
    }

}

Problem seems to be with method getClassNames() . Can you please check fully qualified class name returned from fixName() before loading classes? It will give you better idea what's wrong with the code.

I ran your sample code with hard coded values passed to fixName() (without using getClassNames() ) and it was able to load the class file.

Stupid answer perhaps, but for me the issue was that my project was in a folder which was somehow admin protected.

Which down the line, returns this error!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM