Load all classes in a specific folder without knowing package name - java

六眼飞鱼酱① 提交于 2019-12-02 10:46:54

Two things that come to my mind:

  1. If you want to load classes, the corresponding folder must be in your classpath (can you ensure this -- as you don't know the folder's name?)
  2. If you want to load a class with package a.b.ClassName the file must be located in folder a/b/ClassName.class (otherwise, loading will fail)

update

If you know the folder name, you also know the package name (that's the trick). It must correspond to each other in Java. If a class is in package a.b it must be in folder a/b/. If you only know the root-folder, ie, pathToRootFolder/a/b/ you can search for folders using

File root = new File("<rootFolder>");
File[] files = root.listFiles()

and check each file if it is a directory:

for(File f : files) {
  if(f.isDirectory()) {
    // do processing
  }
}

If there is only one file in a single package structure, there should be only one directory and the name must corresponds to the package name (of course you need to "step into the directory" until there is no further nesting, ie, no sub-folder, and this last folder contains the actual class you want to load. This way to can extract the directory structure and thus the package name.

end update

Some side remarks about your code:

  1. Why // in new File("..//940424//second") (is this a typo and should be \\) [btw: it is better to use File.separator]
  2. Why do you have variable i in your for-loop but actually use classCounter ??
  3. In addedClassName[classCounter] = classFileAdded[classCounter].getAbsolutePath().substring(classFileAdded[classCounter].getAbsolutePath().lastIndexOf("\\")+1); you extract the file name, right? Why you not just use addedClassName[classCounter] = classFileAdded[classCounter].getName()?

you can try this:

Reflections reflections = new Reflections("mysh.im.monitor");
reflections.getSubTypesOf(Monitor.class);

before that, make sure your folder is in your classpath.

maven dependency

<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.9</version>
</dependency>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!