-3

I want to know if I can get the methods that returns class members.

For example I have a class called Person inside this class there is two members that are name and age and inside this class I have 4 methods as follow :

public class Person {

    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}   

so if I use the method Person.class.getDeclaredMethods(); it returns all the methods that are declared inside this class and also Person.class.getDeclaredMethods()[0].getReturnType(); returns the return type of the method.

But what I need is to get the methods that returns the two variables name and age In this case the methods are public String getName() and public int getAge().

What can I do?

Tom
  • 16,842
  • 17
  • 45
  • 54
Sam
  • 149
  • 11

1 Answers1

1

In your class name and age are not global. They would need to have a static before them to be global. In order to access your fields with an instance and reflection you could do something like

public static void main(String args[]) {
    Person p = new Person("Elliott", 37);
    Field[] fields = p.getClass().getDeclaredFields();
    for (Field f : fields) {
        try {
            f.setAccessible(true);
            String name = f.getName();
            String val = f.get(p).toString();
            System.out.printf("%s = %s%n", name, val);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output is (as I would expect)

name = Elliott
age = 37
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249