Take the 2-minute tour ×

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 :)

share|improve this question
quickmeme.com/meme/3p60cd –  Louis Wasserman May 7 '12 at 15:04
add comment

4 Answers

up vote 3 down vote accepted

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.

share|improve this answer
add comment

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).

share|improve this answer
Not to mention you have chances of getting hit by a SecurityManager policy on your way to the privates... –  Romain May 7 '12 at 15:08
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer


