What's the most effective way to get a list of dependencies for a Java class at runtime?
Using this (based on ASM ByteCode Manipulator 3.3.1), I can do the following:
final Collection<Class<?>> classes =
getClassesUsedBy(MyService.class.getName(), "com");
This returns references to BasicService
and IService
, but misses ContainerValue
, and that's the issue. I played around with the ASM code but could not figure out how to pick up ContainerValue.
package com.foo.bar;
public class MyService extends BasicService implements IService {
public String invoke(){
return new ContainerValue("bar").toString();
}
As a side note, if I make ContainerValue
the return type on invoke
, it works.
Is there any alternative to using ASM to get a list of dependencies for a class? Why the heck is that so difficult?
Holger's answer seems to work well, but I also found the code a bit cryptic. I did a little research and re-worked Holger's code for clarity and readability. I added a main() as an example, which filters out java.lang dependencies (which seem like clutter to me) and prints the full class names.
}
“Is there any alternative to using ASM to get a list of dependencies for a class?” Well there are several alternatives. One is to implement the operation without additional libraries.
“Why the heck is that so difficult?” It’s not that difficult. But you should not judge by looking at a mighty library intended for lots of different use cases when you need it for a rather tiny task.
Here is a piece of code performing the entire dependency scan in a straightforward manner. It’s quite efficient but will become a nightmare once you want it to do other things than that. So once you need other byte code operations I recommend turning back to use a library for it.