How to get a list of packages and / or classes in the classpath?

In Java, I can use ClassLoader to get a list of already loaded classes and packages of these classes. But how do I get a list of classes that can be loaded, i.e. Are you on your way to classes? Same thing with packages.

This is for the compiler; when parsing foo.bar.Baz, I want to know if foo is a package to distinguish it from everything else.

+2
source share
3 answers

Its a bit complicated, and there are several libraries that can help, but mostly ...

  • Look at your class path
  • If you are dealing with a directory, you can search for all files ending with .class
  • If you are dealing with a jar, load the jar up and find all files ending with .class
  • Remove .class from the end of the file, replace "\" with ".". and then you have the full class name.

If you have spring in your classpath, you can take advantage of them by doing most of this already:

ArrayList<String> retval = new ArrayList<Class<?>>(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resolver); String basePath = ClassUtils.convertClassNameToResourcePath("com.mypackage.to.search"); Resource[] resources; try { resources = resolver.getResources("classpath*:" + basePath + "/**/*.class"); } catch (IOException e) { throw new AssertionError(e); } for (Resource resource : resources) { MetadataReader reader; try { reader = readerFactory.getMetadataReader(resource); } catch (IOException e) { throw new AssertionError(e); } String className = reader.getClassMetadata().getClassName(); retval.add(className) } return retval; 
+3
source

I think the org.reflections library should do what you want. It scans the class path and allows you, for example, to get all classes or only those that extend a particular supertype. From there it should be possible to get all available packages.

+3
source

I myself searched for this answer, but this is not possible.

The only way I know is that you have all the classes that can be loaded into a specific directory, and then look for it for file names ending in .class.

After that, you can do Class.forName(name_of_class_file).createInstance() for these file names.

+2
source

Source: https://habr.com/ru/post/1238444/


All Articles