Is there is way to print varaible Name instead of varaible value
String Name = "qtpselenium";
i want to print "Name" in console
Instructor
Yogesh Chawla Replied on 10/10/2020
Try this. This will work.
/**
* A Field provides information about, and dynamic access to, a single field of
* a class or an interface.
*
* The reflected field may be a class (static) field or
* an instance field.
*
* @author ychaw
*
*/
public class Class1 {
public int i = 5;
public Integer test = 5;
public String abc = "abc";
public static String testStatic = "THIS IS STATIC";
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
Class1 t = new Class1();
for (Field f : t.getClass().getFields()) {
System.out.println(f.getGenericType() + " " + f.getName() + " = " + f.get(t));
}
}
}
Hi
I have a class where i have declared multiple variables like
public static string name ="qtp";
...
...
...
i have a mehod - i want to print a particular Variable name in the method
Instructor
Yogesh Chawla Replied on 10/10/2020
Try this:
public class Class1 {
public int i = 5;
public Integer test = 5;
public String abc = "abc";
public static String testStatic = "THIS IS STATIC";
public static String name ="qtp";
public void getVariableNames() {
Field[] fields = Class1.class.getDeclaredFields();
//gives no of fields
System.out.println(fields.length);
for (Field field : fields) {
//gives the names of the fields
System.out.println(field.getName());
}
}
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
Class1 t = new Class1();
for (Field f : t.getClass().getFields()) {
System.out.println(f.getGenericType() + " " + f.getName() + " = " + f.get(t));
}
t.getVariableNames();
}
}