【问题标题】:How to get the methods that return the class members? [duplicate]如何获取返回类成员的方法? [复制]
【发布时间】:2015-01-04 21:42:48
【问题描述】:

我想知道我是否可以获得返回类成员的方法。

例如,我有一个名为 Person 的类,在这个类中有两个成员 nameage,在这个类中我有 4 个方法如下:

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;
    }
}   

所以如果我使用Person.class.getDeclaredMethods(); 方法,它会返回在这个类中声明的所有方法,并且Person.class.getDeclaredMethods()[0].getReturnType(); 也会返回该方法的返回类型。

但是我需要的是获得返回两个变量nameage的方法,在这种情况下,方法是public String getName()public int getAge()

我能做什么?

【问题讨论】:

  • 定义全局变量.
  • 那些不是全局变量,它们是类的成员变量。
  • 全局变量NameAge
  • @Sam 是的......这就是你学习的方式,我们在这里互相帮助和纠正。
  • 好的@MarounMaroun 谢谢:)

标签: java class object methods


【解决方案1】:

在您的班级中,nameage 不是全球性的。他们需要在他们之前有一个static 才能成为全球性的。为了使用实例和反射访问您的字段,您可以执行类似的操作

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();
        }
    }
}

输出是(如我所料)

name = Elliott
age = 37

【讨论】:

  • 感谢它的工作可能
  • @Sam 注意上面是直接访问字段;也可以通过方法调用,但它有点复杂 - 特别是如果你想要成员值本身。
  • 是的,如果可能的话,我想要任何对象的成员值
  • 这就是这段代码给你的。
猜你喜欢
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多