1

I have a class and i want to find all variable and type data.

for e.g

class ex
{
    String A,B;
    public void method()
    {
        int a;
        double C;
        String D;
    }
}

so i want output like this

A : String
B : String
a : int
C : double
D : String
Anderson Vieira
  • 8,919
  • 2
  • 37
  • 48
hendrianto
  • 13
  • 4

3 Answers3

2

You can use the methods Class.getDeclaredMethods() and Class.getDeclaredFields() from the Reflection API to list a class methods and attributes.

for (Method m : ExampleClass.class.getDeclaredMethods()) {
    System.out.println(m.getName() + ": " + m.getGenericReturnType());
}

for (Field f : ExampleClass.class.getDeclaredFields()) {
    System.out.println(f.getName() + ": " + f.getType());
}

But you can not normally access the local variables information. In Java 8, you have access to the methods parameters using the method Method.getParameters(). So you could do:

for (Method m : ExampleClass.class.getDeclaredMethods()) {
    for (Parameter p : m.getParameters()) {
        System.out.println(p.getName() + ": " + p.getType());
    }
}

The parameter names are not stored by default in the .class files though, so the parameters will be listed as arg0, arg1, etc. To get the real parameter names you need to compile the source file with the -parameters option to the javac compiler.

Anderson Vieira
  • 8,919
  • 2
  • 37
  • 48
  • sir i still can't get the local variable with your solution,have any idea for get the local variables sir?thanks – hendrianto Apr 06 '15 at 06:39
  • @hendrianto The only local variables that you can normally access are the parameters. You could get some information about the others if you compile your program in debug mode and use a bytecode library. Check [this other answer](http://stackoverflow.com/questions/6816951/can-i-get-information-about-the-local-variables-using-java-reflection). – Anderson Vieira Apr 06 '15 at 11:40
0

check reflection, you can get all the info of a class on runtime

Dani
  • 161
  • 4
0

You can use reflection to get A and B for sure. But you can't get same info for other local variables.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115