0

The code

import java.beans.*
for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
    if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
        System.out.println(pd.getReadMethod().invoke(foo));
}

This code returns the getters of the class but I am trying to access the getters in the order of attributes where I can set their values to.

How can I access the getters in particualr order?

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
rashidali
  • 330
  • 1
  • 5
  • 16
  • What order are you expecting? The JVM does not guarantee any specific ordering. – Chris K Oct 11 '16 at 11:27
  • @ChrisK In case if I have id , name , I would like to getid() and then getName(). but the code above doesn't provide any specific order – rashidali Oct 11 '16 at 11:30
  • Have you considered sorting, using a custom comparator? eg https://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/ – Chris K Oct 11 '16 at 11:32

1 Answers1

0

DEfine the class, then in the instance get all the methods then use a stream to filter the getters only

public class Pint {

    private int x;
    private int y;
    private int z;

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getZ() {
        return z;
    }

and then

 Arrays.stream(p.getClass().getDeclaredMethods()).filter(x -> x.getName().contains("get")).forEach(System.out::println);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97