0

I'm wondering if there is an efficient way to check all the parts of a Java object at once without calling on each one. So let's say I have this example:

Example(boolean part1, int part2, boolean part3)

and I created this Example object:

Example(true, 6, false)

I plan on making a String array that would hold all these values that would look like:

"true", "6", "false"

Would it be possible to make a loop that would grab each part of this object?

StaticBeagle
  • 5,070
  • 2
  • 23
  • 34
  • Is `Example(...)` a constructor call? – smac89 May 18 '20 at 02:04
  • So you essentially want to iterate over class fields? I don't think this is possible without reflection, i.e. https://stackoverflow.com/questions/2126714/java-get-all-variable-names-in-a-class – Jerred Shepherd May 18 '20 at 02:07

1 Answers1

1

You can use Reflection get the fields of the class and loop over the fields array and call setAccessible(true) to allow access if the field is private and get its value

 static class Example {

        private boolean part1;
        private int part2;
        private boolean part3;

        public Example(boolean part1, int part2, boolean part3) {
            this.part1 = part1;
            this.part2 = part2;
            this.part3 = part3;
        }
    }

, main

    public static void main(String[] args) {
        Example example = new Example(true, 1, false);
        Field[] fields = example.getClass().getDeclaredFields();
        List<String> list = new ArrayList<>();
        for (Field f : fields) {
            f.setAccessible(true);
            try {
                list.add(String.valueOf(f.get(example)));
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        String[] strings = list.toArray(new String[0]);
        System.out.println(Arrays.toString(strings));
    }

, output

[true, 1, false]

More information: Reflection Oracle doc

0xh3xa
  • 4,801
  • 2
  • 14
  • 28