Can someone explain reflections in simple terms?
I don't really understand whats the point of the reflection. I get that it allows you to get the information about the class, but if I know the name of the class and the method why not just create an instance of that class. I searched up it is used in plugin architecture but it still seems questionable since you have to either enforce GC to unload old dll or reload project.
Have you guys used it in production if so when and why?
10 Replies
The difference is that you can do reflection at runtime on arbitrary types.
Sure, if you own all of the code and are working with the types at compile time, there is almost no need to use reflection.
But reflection at runtime opens up a lot of powerful scenarios. For instance, I wrote a plugin system that made heavy use of reflection. It would enumerate all plugin DLLs at runtime, reflect over their types and look for any that implemented a particular interface, then added that as a handler for specific types (specified as attributes inside the plugin's code. Attributes are the kind of metadata you use reflection to examine.)
You could drop a new plugin into the plugins folder and it would get picked up and inserted as a handler...without ever needing to rebuild the original service.
Not sure if that's a "simple" explanation but it's an example of where I have used it.
so you did some kind of dependency injection right?
I wouldn't exactly call what I wrote dependency injection.
Well, I didn't think of it that way. I guess maybe you could call it that.
Another example where reflection is used is in things like the implementation of a JSON library. The JSON library when compiled doesn't know anything about the types it is going to be asked at runtime to serialize. So it uses reflection to examine the types and figure out how to turn them into JSON (or vice versa.)
you mean serialization right?
Yes.
I also have used reflection to access private fields of a class I didn't own. That's usually not a great idea but sometimes you need to for various reasons.
i kind of understood, but i still need to do some more work to get comfortabel with it
and why would you need it?
private field within the existing code or by that referencing dll stuff?
Like, a test program that loaded some DLL that someone else had written but some of the state I needed to validate at runtime was in a private field. Reflection to the rescue.
alright i think i some what get why i would use that, but that is very niche thing
thanks
It's pretty rare to need to use reflection honestly. It's very powerful when you come across a scenario where you do need it, but it's also slow and a bit tricky to write the code sometimes...best avoided until you really need it!
sure. some interviewers ask questions regarding it, thats why i decided to learn. i dont think ill need it in the production any time soon