Hello guys so basically i got a class with attributs : let's take an exemple
public class A {
private String A;
private String B;
private String C;
}
then i used this trick to get the names of the attributs :
Class A obj= new A("hello","hey","bye");
Class c = obj.getClass();
Field[] fields = c.getDeclaredFields();
for(int i = 0; i < fields.length; i )
System.out.println(fields[i].getName());
now the output is going to be :
A
B
C
now i want to try to have access to the values of the attribut using the values of string so my code becomes something like this
for(int i = 0; i < fields.length; i )
System.out.println(obj.fields[i].getName());
and output will become
hello
hey
bye
any guide how to do it ? if it doesn't exist any idea how to access to the values?
CodePudding user response:
Use field.get(obj)
.
If the field is private you need to make it accessibile with field.setAccessible(true)
.
A obj= new A("hello","hey","bye");
Class c = obj.getClass();
Field[] fields = c.getDeclaredFields();
for (Field f : fields) {
System.out.println(f.getName());
f.setAccessible(true);
System.out.println(f.get(obj));
}