1

Is there any way to make java compiler list all the classes used in the compiled source code?

For example, for code:

import foo.bar.Hello;
import java.util.List;

...

Hello hello = ...
String string = ...
List list = ...

I would like to get

java.lang.String
java.util.List
foo.bar.Hello

Edit

  • I want it at compile time (or after compilation finishes), not runtime.

Related

Community
  • 1
  • 1
Jakub M.
  • 32,471
  • 48
  • 110
  • 179
  • 1
    [Reflection](http://docs.oracle.com/javase/tutorial/reflect/). – Maroun Apr 08 '14 at 07:20
  • heard about reflection? – Florescent Ticker Apr 08 '14 at 07:20
  • possible duplicate of [Obtaining a list of all classes used while running a Java application?](http://stackoverflow.com/questions/1522329/obtaining-a-list-of-all-classes-used-while-running-a-java-application), although this obtains the information during the execution of the program, which may not be good enough – Duncan Jones Apr 08 '14 at 07:23
  • 3
    I think he wants DURING compilation, not running. – Kartoch Apr 08 '14 at 07:34

2 Answers2

1

During the compilation is not possible. You will have two choices close to the idea:

  • use a program which print the imports after class compilation. You can write one using BCEL for instance.

  • if you're only interested by the annotation, you can try to add an annotation processor during compilation using APT.

Kartoch
  • 7,610
  • 9
  • 40
  • 68
0

Get all the declared fields. It will return you a Field array from where you can get your desired information about the fields such as field type, field name, filed modifier etc.

For more info read about Field JavaDoc

Try this simple code

    Class<?> clazz = null;
    try {
        clazz = Class.forName("com.x.y.z.ClassName");

        for (Field field : clazz.getDeclaredFields()) {
            System.out.println(field.getName());
            System.out.println(field.getType());

        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
Braj
  • 46,415
  • 5
  • 60
  • 76