Java Dynamic Programming: Reflection Introduction

Source: Internet
Author: User

Use information from running classes to make your programming more flexible

Reflection grants your code access to the internal information of the Java class that is loaded into the JVM, and allows you to write code that works with the selected class during the execution of the program, rather than in the source code. This mechanism makes reflection a powerful tool for creating flexible applications, but be careful that reflection can have significant side effects if used improperly. In this article, software consultant Dennis Sosnoski describes the use of reflection and describes some of the costs of using reflection. Here, you can find out how the Java Reflection API lets you hook into objects at run time.

In the first part, I introduce you to Java programming classes and the loading of classes.

This article describes a lot of the information that appears in the Java Binary class format, and now I'll cover the basics of using the reflection API to access and use this information at run time. In order for developers who already understand the basics of reflection to be interested in these things, I'll also describe some performance comparisons of reflection versus direct access. Using Reflection with and metadata (data describing other data) some of the work of Java programming is different. The special type of metadata that is accessed through the Java language reflection is the description of classes and objects inside the JVM. Reflection allows you to access various classes of information at run time, and it even lets you read and write property fields at run time, and invoke methods of the selected class. Reflection is a powerful tool that allows you to build flexible code that can be assembled at run time without the need to connect the source code between components. Some of the characteristics of reflection also bring some problems. In this chapter, I will explore the reasons why the reflection is not intended to be used in the application, and why it is used. After you understand these pros and cons, you will make decisions when the benefits outweigh the drawbacks.

The first class uses the starting point of the reflection as an instance of the Java.lang.Class. If you work with a predetermined class, the Java language provides a simple shortcut for getting an instance of the class directly. For example:

Class clas = Myclass.class;

When you use this technology, all the work related to loading classes takes place behind the scenes.

If you need to read the class name from an external resource at run time, using this method is not going to work, instead you need to use the class loader to find information about the class, as shown here:

"Name" is the class name to load

Class clas = null;

try {clas = class.forname (name);}

catch (ClassNotFoundException ex) {//Handle exception case

}

Use the Loaded class

If the class is already loaded, you will find information about the class that is currently in. If the class has not yet been loaded, the class loader will load it and return an instance of the recently created class. The Reflection class object on the classes gives you all the basic hooks for reflecting the metadata of the access class. http://hovertree.com/menu/java/

The metadata includes information about the class itself, such as packages and subclasses of the class, as well as the interfaces implemented by the class, as well as the details of the constructors, attribute fields, and methods defined by the class. The following items are often used in programming, so I'll give you some examples of how to work with this information later in this section. For each type in the class's construction (constructor, attribute field, method), Java.lang.Class provides four independent reflection calls to access the class's information in a way that does not.

The standard form of these four calls is listed below, which is a set of calls to find the constructor.

Constructor GetConstructor (class[] params) uses the specified parameter type to obtain a public constructor;

Constructor[] GetConstructors () obtains all constructors of this class;

Constructor getdeclaredconstructor (class[] params) using the specified parameter type to get the constructor (ignoring the level of access)

Constructor[] Getdeclaredconstructors () gets all the constructors for this class (ignoring the level of access)

Each of these methods returns an instance of one or more java.lang.reflect.Constructor.

The constructor class defines a newinstance method that requires an object data as a unique parameter, and then returns an instance of the original class that was recently created. The object array is the parameter value that is used when the constructor is called.

For example, suppose you have a twostring class with a constructor with a pair of string arguments, and the code looks like this:

public class Twostring {

Private String m_s1, M_s2;

Public twostring (String s1, string s2) {m_s1 = S1; m_s2 = s2;}

}

The following code shows how to get the constructor for the Twostring class and use the string "a" and "B" to create an instance:

class[] types = new class[] {string.class, string.class};

Constructor cons = TwoString.class.getConstructor (types);

object[] args = new object[] {"A", "B"};

twostring ts = (twostring) cons.newinstance (args);

The above code ignores several possible types of exception checks that are thrown by different reflection methods. These exceptions are described in detail in the Javadoc API, so for simplicity I will ignore them in all the code.

When I relate to the theme of the constructor, the Java language also defines a special (or default) constructor shortcut that does not have a parameter, which you can use to create an instance of a class. This shortcut is embedded in the customization of the class as in the following code:

Object newinstance ()? Creates a new instance using the default constructor.

Although this method only allows you to use a special constructor, it is a handy shortcut if you need to. This technique is especially useful when working with JavaBeans because JavaBeans needs to define a common, parameterless constructor. Lookup attribute fields by reflection call the class-type reflection calls the Access property field information, similar to those used to access the constructor, is substituted with the attribute field name in the parameter with the array type:

Use the following method:

Field GetField (String name)--Gets the attribute field with the public level specified by name

Field GetFields ()? Get all attribute fields with the public level for a class

Field Getdeclaredfield (String name)? Gets the property field that is declared by the class specified by name

Field Getdeclaredfields ()? Get all the attribute fields defined by the class

Although similar to the constructor's invocation, there is an important difference when it comes to attribute fields: The first two methods return information about the Public property fields (including those from the superclass) that can be accessed by the class. The latter two methods return all attribute fields declared directly by the class (ignoring the access type of the property field). An instance of Java.lang.reflect.Field returns all the original data types by invoking the defined GetXXX and Setxxx methods, just like normal get and set methods that work with object references. Although the GetXXX method automatically handles data type conversions (such as using the Getint method to get a value of type Byte), it is a priority to use an appropriate method based on the actual property field type. The following code shows how to use the reflection method of a property field to find an attribute field of type int of an object by specifying the property field name and adding 1 to the property field value.

public int Incrementfield (String name, Object obj) throws ... {

Field field = Obj.getclass (). Getdeclaredfield (name);

int value = Field.getint (obj) + 1;

Field.setint (obj, value); return value;

}

This approach begins to show some of the flexibility that can be generated by using reflection, which is better than working with a particular class, and the Incrementfield method passes the object of the class information you are looking for to the GetClass method, and then finds the named attribute field directly in that class. Using reflection to find methods class reflection calls the access method's information very similar to the method of accessing the constructor and field properties:

Method GetMethod (String name,class[] params)--Methods for obtaining the public type specified by the name parameter using the specified parameter type.

Mehtod[] GetMethods ()? Methods to obtain all the public types of a class

Mehtod Getdeclaredmethod (String name, class[] params)? Use the specified parameter type to obtain the method declared by this class, as specified by the name parameter.

Method[] Getdeclaredmethods ()? Get all the methods declared by this class

As with property field calls, the first two methods return methods of public types that can be accessed through instances of this class? includes methods that inherit the Ultra class. The latter two methods return information about the methods that are declared directly by this class, regardless of the type of access to the method.

The Java.lang.reflect.Mehtod instance returned by the call defines an invoke method that you can use to invoke the relevant instance of the definition class.

This invoke method requires two parameters, one is an instance of the class that provides the method, and the other is an array of parameter values that are required to invoke the method.

The following is a more in-depth example than an example of a property field, which shows an example of a method reflection that uses the get and set methods to do an incremental operation on an attribute of type int defined by JavaBean. For example, if the object is an integer type, the Count property defines the GetCount and SetCount methods, then in order to do the increment for this property, you can pass "count" as the parameter name to the calling method. The sample code is as follows:

public int Incrementproperty (String name, Object obj) {

String prop = character.touppercase (Name.charat (0)) + name.substring (1);

String mname = "get" + prop;

class[] types = new class[] {};

method = Obj.getclass (). GetMethod (Mname, types);

Object result = Method.invoke (obj, new object[0]);

int value = ((Integer) result). Intvalue () + 1;

Mname = "Set" + prop;

types = new class[] {int.class};

method = Obj.getclass (). GetMethod (Mname, types);

Method.invoke (obj, new object[] {new Integer (value)});

return value;

}

According to JavaBeans's specification, I converted the first letter of the property name to uppercase, followed by a "get" to establish a method name to read the property value, and a "set" in front of the property name to establish the method name that sets the property value.

JavaBeans's Read method only returns the property value, and the Write method only needs to write the value as a parameter, so I specify the type of the parameter that matches the method. The final specification specifies that the two methods should be of type public, so I used the call form of the public type method of finding the related class. In this example I first use reflection to pass a value of the original type, so let's take a look at how it works. The basic principle is simple: whenever you need to pass a value of a primitive type, you simply replace the corresponding instance of the class that encapsulates the original type (defined in the Java.lang package). This method can be applied to calls and returns. So when I call the Get method in my example, I expect the result to be a property value of the actual int type encapsulated by the Java.lang.Integer class.

Recommendation: http://www.cnblogs.com/roucheng/p/3504465.html

Java Dynamic Programming: Reflection Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.