I would like to get a list of all interfaces in one package, so I wouldn't have to manually update the list of new interfaces. So I thought if it might be possible to get list of all interfaces in given package via reflection. I know that it is possible to get all classes in package, but I don't know how can I do that with interfaces.
Asked
Active
Viewed 2,609 times
1
-
Um, `grep -w interface path/to/package/*.java`? Also, how do you get a list of all classes in a package? The best you can do is list all classes in an package that happen to be packaged in a .jar file, or all that happen to be in a particular (readable) folder. – Ted Hopp Sep 30 '12 at 08:02
-
Might be a dupe of http://stackoverflow.com/questions/3273157/is-it-possible-to-get-a-collection-of-public-interfaces-and-classes-in-a-package?rq=1 – Sep 30 '12 at 08:02
3 Answers
2
If you know how to enumerate all classes in a package, just do it first and then filter the results by calling Class.isInterface()
.
See als

Community
- 1
- 1

Tomasz Nurkiewicz
- 334,321
- 69
- 703
- 674
1
You can (try to) list all the classes in the package. You can then check each class to see if it is an interface with the Class#isInterface()
method.
1
I don't know what you mean with 'manually update the list of new interfaces' exactly, but if you want to simply get a list of all interfaces contained in a specific package and you use spring you could do the following:
// Instantiate new ClassPathScanner, usualy used to get classes annotated with @Service, @Component.
// The false paramater is provided to disable these default filters.
// Since the ClassPathScanningCandidateComponentProvider only scanns for toplevel classes we
// override the default isCandidateComponent Method to return Interfaces instead.
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false) {
@Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
return beanDefinition.getMetadata().isInterface();
}
};
// Filter to include only classes that have a particular annotation.
// Since we disables the default filters we have to provide this one.
// Here we can provide any regex we want, in this case we fillter all provided classes / interfaces.
provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));
// define package to scan.
Set<BeanDefinition> beans = provider.findCandidateComponents("compu.global.hyper.mega.net");
beans.forEach(bd -> {
System.out.println(bd.getBeanClassName());
});

Matthias
- 400
- 1
- 4
- 13