开发者

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

开发者 https://www.devze.com 2022-12-23 11:54 出处:网络
This question already has answers here: What is reflection and why is it useful? (23 answers) Closed 5 years ago.
This question already has answers here: What is reflection and why is it useful? (23 answers) Closed 5 years ago. 开发者_运维问答

I was just curious, why should we use reflection in the first place?

// Without reflection
Foo foo = new Foo();
foo.hello();

// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);

We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?

To make everything dynamic?


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


A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.


You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.

The most common applications are probably these three:

  • Serialization (see, e.g., .NET's XmlSerializer)
  • Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
  • Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)


Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.

e.g. JXPath allows you to navigate objects like this:

//company[@name='Sun']/address

so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.

You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.


It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.


I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.

This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).

After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.


in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.

Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first


some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.

0

精彩评论

暂无评论...
验证码 换一张
取 消