If you are coding in Java, I feel it is very important that you are well versed with the power of reflection. Using reflection can save you good amounts of LOC but at a performance cost.

Recently at work, I had to reset all the member variables of a Java bean to null. One way of accomplishing this is to individually set all the member variables to null. So, if I have 20 variables in my class, I will have to write 20 lines of repetitive, boring, boilerplate code. Using refection, this can be done in a succinct way as below.

Field[] srcFields = this.getClass().getDeclaredFields();
for (Field field : srcFields) {
try {
field.set(this, null);
} catch (IllegalAccessException e) {
logger.error(e);
}
}

This is a very trivial application of reflection. If you know to harness the power of reflection, you can work wonders with your code.

Advertisements