Search code examples
javareflectionclassloader

Load the class on the way


I have a problem. I have a absolute path to my package, for example:

c:\java_project\src\com\myclass\mypackage

In this package is present 3 classes: MyClass1, MyClass2, MyClass3

I need load all classes to List

I load all .java file to List, but I don't understand how this classes load

List<URL> fieldURLs=new ArrayList<URL>();
File pathToClasses = null;
pathToClasses = new File(packageName);
File[] files = pathToClasses.listFiles();

Please help me with this problem


Solution

  • If I understood you correctly:

    List<Class> classes = new LinkedList<>();
    
    for (File file : new File(pathToClasses).listFiles()) {
        classes.add(Class.forName(file.getName().split("\\.")[0])); // if you don't have packages
    }
    
    classes.forEach(System.out::println);
    

    In my folder I got the following results:

    class Class1
    class Class2
    class Class3