Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all dependencies in a Java class

I'm trying to get all dependencies in a Java class, including classes used for generics parametrization and local variables types. So far best framework I've found is apache bcel. Using it I can easily find all fields, method arguments and local variables from byte code. Basically everything except of generics and local variables types. For example, from line List<Point> points = new ArrayList<Point>(); I can only find one dependency - ArrayList using JavaClass.getConstantPool() method from bcel. It can't detect neither List interface nor Point class. I also tried tattletale and CDA, unfortunately without success (the same results). Examining imports is not enough - I need also dependencies from the same package and I can't accept wildcards. I would be grateful for any help.

like image 676
goobar Avatar asked Jun 28 '13 18:06

goobar


1 Answers

I've finally found solution. ASM Bytecode Framework is the right tool to use. Using official tutorial and right example it's quite easy to get all needed dependencies. In the example there is already a visitor class DependencyVisitor which does what I want. To get right formatting I had to change only one method in DependencyVistitor example code, so it adds full class names instead of packages only:

private String getGroupKey(String name)
{
        //Just comment that block so you can get full class names instead of package only
        /*
        int n = name.lastIndexOf('/');
        if (n > -1)
        {
            name = name.substring(0, n);
        }
       */
        // Replace resource char with package separator char        
        packages.add(name.replace("/", "."));
        //packages.add(name);
        return name;
}

Looking at DependencyVisitor code you can easily understand what it does and modify it to your needs. Running it on my example class it gives me nice, useful output: [java.util.ArrayList, java.lang.Object, java.util.List, java.awt.Point, goobar.test.asmhello.TestClass, java.lang.String, java.lang.Integer, java.awt.Graphics, goobar.test.asmhello.TestClass2]. It contains every class and interface I've used and every type used for generics parameterization.

like image 135
goobar Avatar answered Oct 01 '22 23:10

goobar