lundi 3 mai 2021

Loading Java Classes from a Different Directory Using Reflection

I have a little Java program that uses reflection to load metadata about Java classes in a folder. The crux of the program looks as follows:

   File file = new File("/Users/absolutePath/currentFolder");
   String[] files = file.list();
   Class newClass;
   System.out.println("List of classes:");
   for(int i = 0; i < files.length; i ++) {
        // only care about files with .java extension
        if(files[i].endsWith(".java")) {
         try  {
            newClass = Class.forName(files[i].substring(0,files[i].length()-5));
         }
         catch (Exception e)  {
            e.printStackTrace();
         }
       }
   }

This works fine as long as I run the program from inside the current folder (it will display information about all .java classes that are inside the current folder). However, when I change the path to a different Java folder (File file = new File("/Users/absolutePath/differentFolder")) and run the program, I get a ClassNotFoundException. Not sure why it will not work if I try to load classes from a different folder. I understand that it may have something to do with CLASSPATH but it feels like I may be missing something really simple here. Any suggestions will be greatly appreciated. Thank you in advance!





Aucun commentaire:

Enregistrer un commentaire