Chapter 22. Reflection

This chapter introduces the classes in C#'s System.Reflection namespace. We assume that you are familiar with the general concept of reflection and are somewhat familiar with Java's reflection.

Reflection can be thought of as a “back door” way to get information about objects. In OOP, we can call a method on an object simply by knowing that the method exists on the object. Often, though, when we are dealing with objects in a generic fashion, we do not know about their methods in advance, and sometimes we don't even know the object's type. To call a method on any object without having prior knowledge of the object or its methods, we must query all the methods of the object, find the desired method, and invoke it by passing it parameters at runtime.

To accommodate this, a Java or C# object has associated metadata, or information about its data, such as its fields, its methods, and the constructors and interfaces the object implements. Reflection is the ability to query, search, and use this metadata. Because you must go through the additional step of discovering the method, field, or constructor to call, reflection is always slower than directly calling a specific object method, setting the field, or instantiating the object.

Reflection has a number of important uses:

  • Viewing and querying metadata. Many IDEs use reflection on your custom objects in order to categorize your custom methods and fields in a graphical, treelike format.

  • Dynamic invocation. This allows you to get and set fields of an object at runtime and to invoke methods on that object in a generic fashion. A lot of object-relational tools define mappings from object fields and methods to database table columns. These tools use dynamic invocation to call the appropriate methods to set and get fields on an object after its state is loaded from the database. Java programmers will note that this technique is also used in custom JSP tags.

  • Creating custom types. Java programmers may be familiar with the other two uses of reflection but may be surprised that C# allows you to programmatically access and modify the IL and programmatically create a new type or class. This would be equivalent to two Java APIs: one that allows programmatic access to byte code, and a second one to create classes and interfaces. The core JDK 1.3.1 does not have an API for accessing byte code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.120.133