What is the use of reflection in Java/C# etc

This question already has an answer here:

  • What is reflection and why is it useful? 20 answers

  • Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.

    The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.

    As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.

    Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.


    It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.

    Also, many frameworks use reflection to analyze and use your objects. For example:

  • hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
  • you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String , and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
  • parsing annotations is done by reflection

  • 典型的用法是插件机制,它支持在编译时未知的类(通常是接口的实现)。

    链接地址: http://www.djcxy.com/p/47610.html

    上一篇: @autowired注释如何用于私人领域?

    下一篇: Java / C#中反射的用途是什么?