java - List all subpackages of a package -
i looking way list subpackages of arbitrary package in java.
something this:
package basepackage = getpackage("com.mypackage"); for(package subpackage : basepackage.getsubpackages()){ system.out.println(subpackage.getname()); }
is there way it? in advance.
how ide(let's netbeans) it?
update:
i trying find mappers package mybatis. in project, mappers packages has name "*.mappers". example: "a.b.mappers" or "a.b.c.mappers". thing know base package, , not sure how many mappers packages under it.
update: here code trying use reflection library it:
private set<string> getpackagesnames() { reflections reflections = new reflections("com.mypackage"); set<class<? extends object>> allclasses = reflections.getsubtypesof(object.class); set<string> packagenames = new hashset<>(); for( iterator<class<? extends object>> = allclasses.iterator(); it.hasnext(); ) { class<? extends object> subclass= it.next(); packagenames.add(subclass.getpackage().getname()); } return packagenames; }
not sure why not work. no class found here....
update
here code it. kind of slow, performance not big concern in case. have never used spring before, if there better ways it, let me know. thanks.
private static set<string> getpackages(string basepackage) throws ioexception, classnotfoundexception { set<string> packagesnames = new hashset<>(); resourcepatternresolver resourcepatternresolver = new pathmatchingresourcepatternresolver(); metadatareaderfactory metadatareaderfactory = new cachingmetadatareaderfactory(resourcepatternresolver); string packagesearchpath = resourcepatternresolver.classpath_all_url_prefix + resolvebasepackage(basepackage) + "/" + "**/*.class"; resource[] resources = resourcepatternresolver.getresources(packagesearchpath); for( resource resource : resources ) { metadatareader metadatareader = metadatareaderfactory.getmetadatareader(resource); class aclass = class.forname(metadatareader.getclassmetadata().getclassname()); string packagename = aclass.getpackage().getname(); packagesnames.add(packagename); } } return packagesnames; } private static string resolvebasepackage(string basepackage) { return classutils.convertclassnametoresourcepath(systempropertyutils.resolveplaceholders(basepackage)); }
most of code copied how read classes java package in classpath?
i suppose easiest way packages packages of class loader with
package.getpackages()
and filter package name with
packagename.startswith("com.yourcompany.yourpackage")
Comments
Post a Comment