How to list dependencies of a JAR

2019-01-21 08:45发布

is there a tool that can list third party "packages" that contain (third party) classes referenced in the JAR ? Let say that it would recognize what is "home" package from JAR file definition and it would print out a list of fully qualified names of third party classes up to 3rd level that were referenced within the JAR.

org.apache.commons  
org.apache.maven
javax.servlet.jsp
org.eclipse.persistence
org.apache.jackrabbit

the purpose is that I need to find maven dependencies for that JAR file and deploy it as a maven artifact.

8条回答
我想做一个坏孩纸
2楼-- · 2019-01-21 09:45

My first thought was that you could do this by using a class loader to iterate over all the class files in the jar and use reflection to analyse each one for their dependences. However the Class class does not have a method which tells you this information. So the next thought would be to use some sort of bytecode analyser (asm for example) to pull out all the referenced classes from a compile class.

Presuming that you could get this information the next issue would be to back trace the classes to jars. In a sense this would be the easy part because all you would need to do is create a classloader for each jar in your maven repo, or directory or wherever the jars are, and then ask each one in turn if it contained the specific class.

The flaw in that thinking is that a java class (raw source or compiled) does not detail where to get the imported class from. So if you have two classes with the same package and name (happens more often than you might think), then you would be unable to tell which to use.

Even java just assumes that the first one it finds in the class path is the correct one and throws an exception if it turns out to be incorrect (MethodNotFoundException). So unless you are going to further analyse the bytecode to figure out what methods on each class are called and then compare those with the classes in your class path, you still won't be able to be correct.

IN short, it's probably possible to do what you want, but likely to be very difficult and time consuming.

The way I normally deal with this is to simply fire up the class in test code and keep adding dependencies until I can get it to execute every method I'm interested in.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-21 09:51

You can do the following (if its a maven project):

mvn dependency:tree

It shows transitive dependencies as well, making it very useful to debug dependency conflicts.

查看更多
登录 后发表回答