Java reflection mechanism learning notes

Source: Internet
Author: User

1. Functions of the Java reflection mechanism

In the Java Runtime Environment, can I know the attributes and methods of any class? For any
Can an object call any of its methods? The answer is yes. This kind of dynamic retrieval class information and dynamic
The function of calling an object method comes from the reflection mechanism of the Java language. Java reflection mechanism mainly provides
Has the following features:
L determine the class to which any object belongs during running;
L construct objects of any class at runtime;
L judge the member variables and methods of any class at runtime;
L call methods of any object at runtime;
L generate a dynamic proxy.
This chapter first introduces the usage of Java reflection API, and then introduces an example of remote method call.
In this example, the client can remotely call a method of an object on the server. The server uses the reflection mechanism to provide
The client uses the dynamic proxy function provided by the reflection mechanism.

2. Several important classes involved in Java reflection are located in the Java. Lang. Reflect package.

Class class: represents a class. to operate a class through reflection, you must create a Class Object Based on the specified class.

Method class: represents the methods in the class. to operate a method, java. Lang. Reflect provides the method class, you can create a specified

The method object of the method. This object represents this method, which also reflects the idea that everything is an object.

Field Class: represents the member variables of the class.

Constructor class: indicates the constructor class. It is not parsed here, because it can be understood as a method class.

Array class: Used to dynamically create arrays and access array elements

. Use the three steps of the class in the Java. Lang. Reflect package

1. Get a java. Lang. Class object, which is obtained by specifying the class you want to operate. Java. Lang. Class is used as the representative class and interface (

The first step is to obtainjava.lang.Class

Object for the class that you want to

Is used to represent classes and interfaces in a running Java program.

There are three methods to obtain the java. Lang. Class Object:

One way of obtaining a class object is to say:
Class C = Class. forname ("Java. lang. string "); <br/> to get the Class Object for string <br/> another approach is to use: <br/> Class C = int. class; <br/> or <br/> Class C = integer. type; </P> <p>

2. Obtain class information, such as method, field, constructor (the second step is to call a method suchgetDeclaredMethods, To get a list of all the methods declared by the class .).


3. After obtaining information, use the reflection API to perform operations on the information (once this information is in hand, then the third step is to use
Reflection API to manipulate the information. For example ).


4. Understanding of the invoke method in the method class

Method (Java 2 platform SE 6)


Invoke <br/> Public objectinvoke (Object OBJ, object... ARGs) throws illegalaccessexception <br/>, illegalargumentexception <br/>, invocationtargetexception <br/>

This interface is used to call a specified object with specified parameters.Method

The underlying method of the object. Some parameters are automatically decompressed to match the basic parameters. Both basic parameters and reference parameters are subject to method call conversion as needed.

If the underlying method is static, you can ignore the specifiedobj
Parameters. This parameter can be null.

If the shape parameter required by the underlying method is 0args
The array length can be 0 or null.

If the underlying method is an instance method, dynamic method lookup is used to call it. This is recorded in Java language specification, Second Edition
In section of; this should be done in the case of a rewrite of the runtime type based on the target object.

If the underlying method is static and the class that declares this method has not been initialized, it will be initialized.

If the method completes normally, the value returned by the method is returned to the caller. If the value is of the basic type, it is first packaged in the object as appropriate. However, if the value type is a set of basic types, the array elementNo

Wrapped in an object; in other words, an array of the basic type is returned. If the underlying method returns the void type, the call returns NULL.


-The object from which the underlying method is called
-Parameters used for method call
Return Value:
Parameters Used args
In obj
Specifies the result of the method indicated by this object.


The object enforces Java access control, and the underlying method is not accessible.


If the method is an instance method and the specified object parameter is not an instance of the class or interface (or its subclass or implementation program) that declares the underlying method, if the number of real parameters and form parameters is different; if the unpackage conversion of basic parameters fails, if the unpackage is canceled, the parameter value cannot be converted to the corresponding parameter type through method call conversion.


-If the underlying method throws an exception.


-If the specified object is null, this method is an instance method.


-If initialization fails due to this method.

Let's look at a specific example of this method:
  import java.lang.reflect.*;     public class method2 {      public int add(int a, int b)      {         return a + b;      }      public static void main(String args[])      {         try {           Class cls = Class.forName("method2");           Class partypes[] = new Class[2];            partypes[0] = Integer.TYPE;            partypes[1] = Integer.TYPE;            Method meth = cls.getMethod(              "add", partypes);(1)            method2 methobj = new method2();(2)            Object arglist[] = new Object[2];            arglist[0] = new Integer(37);            arglist[1] = new Integer(47);            Object retobj               = meth.invoke(methobj, arglist);(3)            Integer retval = (Integer)retobj;            System.out.println(retval.intValue());         }         catch (Throwable e) {            System.err.println(e);         }      }   }

(1) create an object for the specified method, and (2) Call the underlying method represented by the object
Here we need to have a thought transformation. We created a method2 object in (2). According to our habits, all the methods called by XX are methobj. XX () is called in this way, but we cannot call this method after reflection is used. Instead, this object is treated as a parameter.
First, let's take a look at the explanation of the invoke method: to call a specified object with a specified parameter from this Method

The underlying method of the object.

Analysis: Object retobj = meth. Invoke (methobj, Arglist );
The result of this statement is that the add method is called, but you do not know how to call it directly. "The specified object with the specified parameter" here refers to methoject And Arglist, "This method object" indicates meth. The call method turns into a bend. In short, we must turn our thinking into a new one when using this method. At this time, we no longer need to manually specify the call method, instead, the program automatically calls the method to be called by passing in the subject object and parameters.
Related Article

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: 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.