Mario Ortegón
Mario Ortegón

Reputation: 18900

Determining which classes are used in a Class

I have a class and I want to determine which classes are actually referenced from the class. Is there any easy way to determine which classes are being used directly?

Ideally I should be able to know this before the class is compiled, but it is also valid to know this after the class have been compiled.

I have a runtime system where the user can provide "sequences" that will be executed. These sequences will be executed in Java. However, we want to warn the user if he uses Java Classes that are not included in a pre-approved API.

Upvotes: 2

Views: 114

Answers (3)

fasseg
fasseg

Reputation: 17761

there's a little known Tool in the Java SDK called javap which you can run against any class file and will give you the signature of the class:

consider this class:

public class Test{
    private String name;
    private int someValue;
    private ClassLoader classLoader;
}

Running javap on that class yields:

# javap -private Test

Compiled from "Test.java"
public class Test extends java.lang.Object{
    private java.lang.String name;
    private int someValue;
    private java.lang.ClassLoader classLoader;
    public Test();
}

There you can see all the classes that are used. Dont forget the "-private"-Option or you will only see public, protected and default visible fields/methods

Hope that helped

Upvotes: 3

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

If you have the .class file, use a bytecode parsing library such as BCEL to load the .class file, then look in the Constant Pool to see what classes are referenced (either as class literals or via methods/fields of other classes).

Upvotes: 2

duffymo
duffymo

Reputation: 308763

The best way to do such a thing at runtime is to use aspects. You can configure your aspect to advise based on packages, classes, right down to the method signature. Your aspect can know about the pre-approved packages/classes/methods and advise based on that.

Upvotes: 0

Related Questions