2

I have a package x which contains about 30 classes. The program I am compiling uses 5 classes from package x. How to find the 5 classes which are used during my current compilation at a glance?

My current approach is to inspect the code and see which classes are used/instantiated, this is tedious and slow as I have to manually go through the code. Is there a better approach to find all classes which are used during my current compilation?

I want to press a button and see all classes which are required for the compilation of my program.

TylerH
  • 20,799
  • 66
  • 75
  • 101
PlsWork
  • 1,958
  • 1
  • 19
  • 31

1 Answers1

2

How about this command:

# which jar file you need analyzing
export JAR_FILE="...";
# export CLASSPATH environment for compiling purpose
export CLASSPATH="...";

javac -verbose *.java 2>&1 \
     | grep -E "^\[loading" \
     | grep $JAR_FILE \
     | grep -Eo "\((.*?)\)";

Example

compiling Main.java:

public class Main {
   public static void main(String[] args) {
      org.joda.time.DateTime dateTime = new org.joda.time.DateTime();
   }
}

with commands below:

export JAR_FILE="joda-time-2.9.9.jar";
export CLASSPATH="joda-time-2.9.9.jar";
javac -verbose *.java 2>&1 \
     | grep -E "^\[loading" \
     | grep $JAR_FILE \
     | grep -Eo "\((.*?)\)";

will outputs the classes that used in joda.jar only:

(org/joda/time/DateTime.class)

holi-java
  • 29,655
  • 7
  • 72
  • 83
  • 1
    Can it be achieved with an IDE (Eclipse) ? – c0der May 22 '17 at 06:45
  • 1
    @c0der many IDE has code anaylzer plugins too. For eclipse you can find [here](http://marketplace.eclipse.org/category/categories/source-code-analyzer). – holi-java May 22 '17 at 06:48
  • This is exactly what I need, I would like to do it out of eclipse (with a plugin if it's not supported out of the box by eclipse), do you have any recommendations for plugins? – PlsWork May 22 '17 at 11:06
  • 1
    @AnnaVopureta maybe you need extends with [jdeps](https://wiki.openjdk.java.net/display/JDK8/Java+Dependency+Analysis+Tool) or [here](http://stackoverflow.com/questions/4326407/analyze-jar-dependencies-in-a-java-project). you can google to find with "java class usage analyzer lib" to meet your needs. – holi-java May 22 '17 at 11:11