Finding a Java class in a package recursively by name

Is there a simple, well-studied way to search for a given class by name in a package and, recursively, in all subpackages of this package?

those. taking into account existing classes, for example:

  • foo.MyClass
  • foo.bar.baz.some.more.MyClass
  • foo.bar.baz.some.more.OtherClass

I would like to run something like magicMethod("foo.bar.baz", "MyClass")and get Class foo.bar.baz.some.more.MyClassas a result.

Obviously, it’s quite easy to implement it manually - by examining the downloaded packages from Package.getPackages(), filtering whatever is suitable and searching for the class in a loop using Class.forName(...)- but there might be something in the standard Java libraries or some other widespread library such as Apache Commons who solve this problem?

+3
source share
1 answer

OSS: https://bitbucket.org/stevevls/metapossum-scanner/wiki, maven.

, :

Set<Class<? extends MyDiscoverableHelper>> implementingClasses = new ClassesInPackageScanner()
    .findImplementers("com.mypackage.service.impl", MyDiscoverableHelper.class);

:

Set<Class> entityClasses = new ClassesInPackageScanner()
    .findAnnotatedClasses("com.mypackage.datamodel", javax.persistence.Entity.class);

. , :

Set<Class> entityClasses = new ClassesInPackageScanner().setResourceNameFilter(new ResourceNameFilter() {
    public boolean acceptResourceName(java.lang.String packageName, java.lang.String fileName) {
        return fileName.equals("MyClass.class");
    }
}).scan("foo");

, , . , API, , , API.

, () , . , !

+5

All Articles