PositiveGuy
PositiveGuy

Reputation: 47743

Applicability of Reflection

There are some great articles out there such as this one on Reflection.

What I want to know is real world examples where it is used and real world reasons or when it's useful and why outside the raw "you can get type info"...I get all that in this article and others.

Ok, so what, it doesn't really help me in context to actual programming situations. I'm trying to figure out how people are using it in apps, good examples of times that they have been used just to get my head wrapped around when you'd want to use it.

Upvotes: 1

Views: 244

Answers (4)

sleske
sleske

Reputation: 83609

As pointed out by Mehrdad, run-time plugins are one are where reflection is used. A good example is the JDBC API. You use reflection to load the driver class by name; that's the only way to do it, as the JVM cannot know which class to load on its own.

Another situation where reflection is useful is for application frameworks that are supposed to run arbitrary code. Examples:

  • application servers
  • unit testing frameworks (JUnit uses reflection extensively)
  • RPC-type applications (e.g. XML-RPC)

Yet another is persistence frameworks, which can load/save arbitrary class instances (e.g. Hibernate).

Upvotes: 1

limc
limc

Reputation: 40168

A good real-life example of reflection is Spring's Inversion of Control (IoC) framework in Java where you can wire your beans using XML configurations.

Upvotes: 1

user111013
user111013

Reputation:

Reflection is also useful when you are dealing with serialization.

Just recently I had to write some very custom serialization code for talking to a third party service, this meant using reflection to find properties, and determine whether the property was eligible to be serialized depending on the attribute.

Upvotes: 1

user541686
user541686

Reputation: 210445

Reflection is useful for run-time plugins. When you make a program that can be extended via plugins, by definition you don't know what the classes and methods are at compile-time, so you use reflection to load the libraries at run-time and then call the appropriate methods.

Upvotes: 3

Related Questions