0

So is this faster:

for (int i = 0; i < example.length; i++) {
    switch (i) {
        case 0: return example.field0;
        case 1: return example.field1;
        case 2: return example.field2;
        case 3: return example.field3;
        case 4: return example.field4;
        case 5: return example.field5;
        case 6: return example.field6;
        case 7: return example.field7;
        case 8: return example.field8;
        case 9: return example.field9;
        case 10: return example.field10;
    }
}

Or this:

for (int i = 0; i < example.length; i++) {
    return example.class.getField("field" + i);
}

I just want to know because it seems a bit tedious doing the first one and I do not want to repeat lots of lines of code that are basically doing the exact same thing.

Kailee Zhang
  • 33
  • 1
  • 5
  • 5
    Looks like you want to use neither as this looks to be a great case for use of a `Map` such as a `HashMap`. Also please understand that reflection is very expensive. – Hovercraft Full Of Eels Jun 11 '17 at 22:59
  • 6
    Both cases (as posted) can be greatly simplified. They're equivalent to `return example.field0;` since when `i == 0` that is what you return (and both loops start with `i` equal to `0`). – Elliott Frisch Jun 11 '17 at 23:20

1 Answers1

0

What exactly is field0...field10? Depending on the relation between these fields, you might want to organize them in an appropriate data structure.

  • Do you have 11 fields of the same type and (besides their index) the same meaning, like the x-coordinates of the points of a line. Then an Array or a List might be the correct data structure.

  • Do these 11 fields cover the same aspect of the object and could be considered to belong together but can be named individually, like e.g. metadata of a document. The you might use a map (as "Hovercraft Full Of Eels" suggests) or put them into their own object. If you put the fields into a map, you might want to use an enumeration as key.

  • Are these 11 fields basically independent of each other? Then please don't try to access them together but write a getter and setter per field.

"Tedious" and "many lines of code" is not a good guide. It may be a sign of a bad design that should be corrected (see above). Otherwise there's usually a workaround in your favorite IDE. Creating setters and getters should only be a click away!

Please use reflection only if there's no other way. For examples see How could Reflection not lead to code smells?. Reflection in Java has quite a few drawbacks: bad performance, complex and difficult to get right. The main argument against reflection is IMHO that the compiler and IDEs are not made for reflection. You rename field<x> to metadata<x>? The refactoring will not change [...] getField("field" + i); and the compiler will not complain!

But to answer the actual question: Reflection is most likely a lot slower than direct Java code.

sruetti
  • 532
  • 2
  • 7