-1

Is there a way to check for all class files in a folder and create a new object for each file if it exists in the folder? For java...

Tilion
  • 103
  • 4
  • 10
  • You can use [reflections](https://code.google.com/p/reflections/) library to achieve that. – Piotr Praszmo Dec 27 '14 at 16:51
  • [Finding files in directory](http://stackoverflow.com/questions/4852531/find-files-in-a-folder-using-java) [Creating new instances using reflection](http://stackoverflow.com/questions/2566754/dynamically-class-creating-by-using-java-reflection-java-lang-classnotfoundexce) – Illyes Istvan Dec 27 '14 at 16:55

1 Answers1

1

Here is sample for invoking classes from directory.

public class InvokeClass {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {

        try {
            String classDerectory = "C:\\classes";
            File folder = new File(classDerectory);
            // read derectory 
            for (final File fileEntry : folder.listFiles()) {
                // URLClassLoader so convert file to url
                URLClassLoader classLoader = new URLClassLoader(new URL[]{fileEntry.toURI().toURL()});
                //get class from loader
                Class<?> clazz = classLoader.loadClass(fileEntry.getName());
                // get new instance
                Object obj=clazz.newInstance();
                // do something with object.......
            }


        } catch (Exception e) {
            // something went wrong..
            e.printStackTrace();
        }

    }
}
JBaba
  • 590
  • 10
  • 30