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
3 Answers 3
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.
-
sir i still can't get the local variable with your solution,have any idea for get the local variables sir?thankshendrianto– hendrianto04/06/2015 06:39:18Commented 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.Anderson Vieira– Anderson Vieira04/06/2015 11:40:49Commented Apr 6, 2015 at 11:40
check reflection, you can get all the info of a class on runtime
-
you can't use reflection to get local variables here.Ruchira Gayan Ranaweera– Ruchira Gayan Ranaweera03/24/2015 10:58:47Commented Mar 24, 2015 at 10:58
You can use reflection
to get A
and B
for sure. But you can't get same info for other local
variables.
-
so how can i get the local variables sir?hendrianto– hendrianto04/06/2015 06:38:03Commented Apr 6, 2015 at 6:38