Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is using reflection a good practice? [closed]

I recently learned about reflection in my course and was given an assignment to create objects from an XML file using reflection in Java. Through searching this site I'm noticing there seems to be a general consensus that using reflection, particularly in this way, is a bad idea. Odd to me because we were told this is one of the most useful things we'll learn this semester.

I have no control over my assignment so I'll just have to complete it this way anyhow. But I was wondering, when is using reflection a good practice? And what are some industry examples you might have where reflection was the best way to go about a problem?

like image 949
Sithe Avatar asked Mar 10 '23 12:03

Sithe


1 Answers

Reflection is a tool, you should use it when you need it, an use others where more appropriate.

When is appropriate to use reflection? When you are dealing with instance of object or classes which have some common behavior which is not enforced by interfaces.

The simplest example is POJO, you very often use classes which are just a collection of fields and their getter and setter, they much behave in the same manner, but you cannot define their common behavior with inheritance.

There are hundreds of tools that leverage that behavior building pojos from scratch, or setting fields, and they use reflection.

Examples: GSON, JAXB, Hibernate, Spring, Weld ... etc.

Reflection is more difficult to write, more difficult to debug, and test, give you pretty scary and uninformative stack traces, but let you deal with more general common behavior then inheritance.

A side note, since the introduction of annotations reflection has become less scary, because you can decorate classes with information that let you do reflection with a more reliable approach, in fact all the framework I cited use annotations.

Last but not least, you don't use reflection much all the same, because you need it for meta programming and, most of the time, meta programming has been done for you by others (see GSON, JAXB, Hibernate, Spring, Weld ... etc), so in fact you will find difficult to find a problem general enough to be solved with reflection, and has not been solved by others.

like image 167
minus Avatar answered Mar 21 '23 02:03

minus