2

I've just discovered that reading and writing any private field of any object could be done without any accessor, but using reflection.

So, my question is: in the case of an application which uses no third technology (e.g. EL) but JAVA, if I need a POJO that contains let say 20 fields, is it more interesting to implement 40 accessors, or to use reflection to access them? I guess some pros and cons, but any experience or feedback would be great :)

sp00m
  • 47,968
  • 31
  • 142
  • 252

4 Answers4

4

You can, but it wouldn't be very maintainable, so: don't do it. The advantages of using getter/setter to access members is, that you are able to hide the accessor, initialize lazy and you will be able to refactor easily (e.g. with IDEA or Eclipse).

Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45
  • 1
    Not to mention you have chances of getting hit by a SecurityManager policy on your way to the privates... – Romain May 07 '12 at 15:08
3

It's generally better to access your fields through getters, even if you're using reflection to figure out what fields are available. You can just as easily figure out what getters are available via reflection and call those getter methods. This allows you to:

1) Dynamically figure out what data is available.

2) Explicitly state which fields should be made available and which fields should be private.

3) Explicitly override a getter's behavior to suit your needs.

In most normal cases, reflection is used for figuring out what data is available on an object. You should not use reflection as a general replacement for getters and setters. Otherwise, your code will become truly unmaintainable.

Tim Pote
  • 27,191
  • 6
  • 63
  • 65
3

You can access object fields and methods using reflection, but you should not.

This article lists at least 2 measurable reasons why not:

  • Performance. Accessing object methods/fields using reflection is slower than accessing via accessors.

  • Security restrictions

  • And the greatest drawback is non-maintainability, quoting from the article below:

A more serious drawback for many applications is that using reflection can obscure what's actually going on inside your code. Programmers expect to see the logic of a program in the source code, and techniques such as reflection that bypass the source code can create maintenance problems.

Ozair Kafray
  • 13,351
  • 8
  • 59
  • 84
1

Reflection is only good for specific use cases where one needs to do magic on objects without being able to assume a lot about their structure. Specifically, if your JVM uses a SecurityManager, it might very well prevent code to set privates through reflection.

You could look at this other question for more information about the security manager.

Community
  • 1
  • 1
Romain
  • 12,679
  • 3
  • 41
  • 54