Jakub M.
Jakub M.

Reputation: 33867

List all the classes used - compile time

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

Related

Upvotes: 1

Views: 313

Answers (2)

Kartoch
Kartoch

Reputation: 7779

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.

Upvotes: 1

Braj
Braj

Reputation: 46871

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();
    }

Upvotes: 0

Related Questions