Question
How would I determine, either during or after bean discovery, from which bean archive a bean originated, without relying on implementation specifics (if possible)?
Elaboration
Within the Jakarta CDI and Java EE CDI specifications there are references to "Bean Archives". To the best of my understanding a Bean Archive is any Java Archive which contains a beans.xml (explicit bean archive) or has classes that have been annotated with a bean defining annotation.
As far as I know, neither CDI specification (Jakarta nor Java EE) has added the concept of a bean archive as part of its API definition.
Some CDI implementations such as Weld have classes/interfaces for the concept of bean archives (e.g. BeanArchives, BeanDeploymentArchive), but I'd rather not rely on implementation specifics.
As for any possible answers. I don't have any restrictions as to a possible implementation as I am in full control of the CDI container. Whether it would take the form of an extension, interceptor or decorator, I really don't mind.
You can get a working list of archives by doing:
someClassLoader.getResources("/META-INF/beans.xml");
…and then ensuring that those are in fact valid beans.xml
files (or you can just decide to trust the environment). Then you have to deal with jar:
URLs in most cases and relativize the resulting URLs by hand, and normalize them, and so forth and so on, but that will give you some classpath roots that probably have beans in them.
You can get the effective location of most classes, but not all, by doing:
someClass.getProtectionDomain().getCodeSource().getURL();
(That's the brief version, and you will, in reality, have to handle potential null
s along the way but you get the idea.)
From those two recipes perhaps you can get close to whatever it is you want. Note that there are many ways each of these can fail, but for a "normal" situation involving jar files in a non-modular Java application running with ordinary classloaders and so on, and for cases where the beans you're interested in are not synthetic, you might be able to mostly rely on this. (Recall that beans can be programmatically added, so I'm not sure what you would want to do in such a (common) situation.)