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
9,0692 gold badges39 silver badges48 bronze badges
asked Mar 24, 2015 at 10:40

3 Answers 3

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.

answered Mar 24, 2015 at 11:01
2
  • sir i still can't get the local variable with your solution,have any idea for get the local variables sir?thanks Commented Apr 6, 2015 at 6: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. Commented Apr 6, 2015 at 11:40
0

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

answered Mar 24, 2015 at 10:44
1
  • you can't use reflection to get local variables here. Commented Mar 24, 2015 at 10:58
0

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

answered Mar 24, 2015 at 10:58
1
  • so how can i get the local variables sir? Commented Apr 6, 2015 at 6:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.