Hello everybody :slightly_smiling_face: is there i...
# ksp
o
Hello everybody 🙂 is there in the KSP opportunity to get all subtypes (subclasses/subinterfaces) for some
KSCLassDeclaration
in case if that declaration is no sealed?
j
you can try to collect all class declarations in the source code and check if they are subtypes of your query. Performance won’t be good though, as you will be resolving all class declarations.
g
Is there a way to get all class declarations from all modules to be able to collect all subclasses of an interface? (not only the compilation module but also the dependencies) If not I presume I've to generate for each modules a hierarchy tree file, so that from KSP I can scan all hierarchy files from my project. But it's limited to the project and won't scan external dependencies, right?
m
I don't think so - you can use resolver.getAllFiles, but this is only going to give you what is in the current compilation (which might not be the whole module when partial compilation is in use). Also: this approach creates a potential trap: Mod A: has interface Mod B (depends on Mod A), runs KSP, generates something based on interface that is in Mod A Mod C (depends on Mod B) : runs KSP, also generates something based on interface that is in mod A, now you might have a conflict because you probably generated the same thing twice.
g
I was thinking more like: Mod A: generates a hierarchy file (in this example, nothing there) Mod B: generates a hierarchy file (in this example, "ClassB inherits InterfaceA") Mod C: application module, so we search for all hierarchy file ("ClassB inherits InterfaceA")+ module compilation data ("ClassC inherits InterfaceA"), so that HERE I can have all subclasses of a given interface.
m
Two possibilities I can see: 1. Use resolver.getAllFiles - search through everything being compiled to generate a hierarchy for the modules being compiled. Of course you'd need to make sure that whatever Mod A and B generate don't conflict. Maybe could be done by passing arguments to the annotation processor. 2. Depending on the platform / use case / runtime performance required, might be better done using reflection at runtime: https://github.com/ronmamo/reflections - this has an API to look for subtypes on the classpath: https://www.baeldung.com/reflections-library#2-adding-scanners
g
Thanks Mike, eventually I used reflection for my little need, but it would have be really better to have that from KSP directly (as it's an open-source project that can do 95% of the work with KSP but would require runtime with slow operation to make that last step... so still searching something smarter without killing perfs)
t
If the package names of subclasses are known, Resolver.getDeclarationsFromPackage might be useful. It's no quicker than a properly implemented reflection solution, but you pay it at compile time instead of runtime.
👍 2