Java. Lang. Reflect package Introduction

Source: Internet
Author: User
I hereby declare that the original content of these materials comes from www.java.sun.com. I only translate and organize the content based on my understanding.
I. Overview
The reflection API allows Java code to dynamically query and operate running Java classes or interfaces. Reflection contains many classes, such as the method class, which can be found in the Java. Lang. Reflect package.


Three steps are required to use the class in reflection:

1. Get the object of the class to be operated. The object belongs to the java. Lang. Object package. This object represents a running class or interface. The following three methods are commonly used to obtain class objects:

(1) Class C = Class. forname ("Java. Lang. String ");

Use the. forname method to load a class, which is a string class to obtain a class object corresponding to the class.

(2) Class C = int. Class;

(3) Class C = integer. type;

2. Get the declared method of the class object to be manipulated

The simplest and most common method for getting class objects is the getdeclaremethods () method. This method returns an array of methods (method []) of all methods declared in the class object. Other methods will be introduced later.

3. Use reflection API operation class.

Ii. java. Lang. Reflect package Introduction
The Java. Lang. Reflect package contains two interfaces and eight classes.

Invocationhandler interface:

Member interface: this interface can  about the constructors of class members (fields or methods.

Accessibleobject class: this class is the basic class for field objects, method objects, and constructor objects.

Array class: This class provides methods to dynamically generate and access Java arrays.

Constructor class: Provides the constructor information of a class and the constructor interface of the class.

Field Class: provides information about the domain of a class and the interface of the domain of the category.

Method class: provides information about the methods of a class and interfaces of the methods of the category class.

Modifier class:

Proxy class: provides static methods for dynamically generating proxy classes and class instances.

Reflectionpermission class:

Iii. Examples and instructions
3.1 search for all methods declared in the class
Import java. Lang. Reflect .*;

Public class Method1 {

Private int F1 (

Object P, int X) throws nullpointerexception

{

If (P = NULL)

Throw new nullpointerexception ();

Return X;

}


Public static void main (string ARGs [])

{

Try {

Class CLS = Class. forname ("Method1 ");


Method methlist []

= Cls. getdeclaredmethods ();

For (INT I = 0; I <methlist. length;

I ++ ){

Method M = methlist [I];

System. Out. println ("Name

= "+ M. getname ());

System. Out. println ("Decl class =" +

M. getdeclaringclass ());

Class PVEC [] = M. getparametertypes ();

For (Int J = 0; j <PVEC. length; j ++)

System. Out. println ("

Param # "+ J +" "+ PVEC [J]);

Class evec [] = M. getexceptiontypes ();

For (Int J = 0; j <evec. length; j ++)

System. Out. println ("exc #" + J

+ "" + Evec [J]);

System. Out. println ("return type =" +

M. getreturntype ());

System. Out. println ("-----");

}

}

Catch (throwable e ){

System. Err. println (E );

}

}

}

Code Description:

Class CLS = Class. forname ("Method1"); obtain the Class Object cls of the Method1 class.

Method methlist [] = Cls. getdeclaredmethods (); returns an array of methods for all methods declared by a class.

M. getdeclaringclass (); returns an instance of the class that declares this method. The returned value is a class.

M. getname (): returns the name of The method. The returned value is of the string type.

Class PVEC [] = M. getparametertypes (): returns an array of the type of the parameters of this method. Note that the return order of parameters is the same as that of method declaration.

Class evec [] = M. getexceptiontypes (): gets an array of types for exceptions thrown by this method.

M. getreturntype (): Type of the return value of this method. The returned value is a class.

In addition to the methods of the above method class, there are other methods. Among them, the most important ones are:

Object invoke (Object OBJ, object [] ARGs) method: Call and execute the method. The meanings of the two parameters are a class instance object that calls the method, and an array of parameter objects that call the method. For more information about the application, see section 3.4.

3.2 obtain the constructor Information
Import java. Lang. Reflect .*;


Public class constructor1 {

Public constructor1 ()

{

}


Protected constructor1 (int I, double D)

{

}


Public static void main (string ARGs [])

{

Try {

Class CLS = Class. forname ("constructor1 ");


Constructor ctorlist []

= Cls. getdeclaredconstructors ();

For (INT I = 0; I <ctorlist. length; I ++ ){

Constructor Ct = ctorlist [I];

System. Out. println ("Name

= "+ CT. getname ());

System. Out. println ("Decl class =" +

Ct. getdeclaringclass ());

Class PVEC [] = CT. getparametertypes ();

For (Int J = 0; j <PVEC. length; j ++)

System. Out. println ("Param #"

+ J + "" + PVEC [J]);

Class evec [] = CT. getexceptiontypes ();

For (Int J = 0; j <evec. length; j ++)

System. Out. println (

"Exc #" + J + "" + evec [J]);

System. Out. println ("-----");

}

}

Catch (throwable e ){

System. Err. println (E );

}

}

}

Constructor ctorlist [] = Cls. getdeclaredconstructors (): obtains an array of all constructors declared by the instance object.

Ct. getname (): get the name of the constructor. The returned value is a string type variable.

Ct. getdeclaringclass (): return the class that declares the constructor. The returned value is a class.

Class PVEC [] = CT. getparametertypes (): returns an array of types for the parameters of the constructor. Returns an array of the class type.

Class evec [] = CT. getexceptiontypes (): returns an array of types with exceptions thrown by the constructor.

In addition to the above methods, there is also an important method for the constructor class:

Object newinstance (Object iniargs []): actually calls this constructor and generates an instance object. For specific applications, see section 3.5.

3.3 obtain domain information in the class
Import java. Lang. Reflect .*;


Public class field1 {

Private double D;

Public static final int I = 37;

String S = "testing ";


Public static void main (string ARGs [])

{

Try {

Class CLS = Class. forname ("field1 ");


Field fieldlist []

= Cls. getdeclaredfields ();

For (INT I

= 0; I <fieldlist. length; I ++ ){

Field identifier = fieldlist [I];

System. Out. println ("Name

= "+ Response. getname ());

System. Out. println ("Decl class =" +

Response. getdeclaringclass ());

System. Out. println ("Type

= "+ Response. GetType ());

Int mod = parser. getmodifiers ();

System. Out. println ("modifiers =" +

Modifier. tostring (MOD ));

System. Out. println ("-----");

}

}

Catch (throwable e ){

System. Err. println (E );

}

}

}

3.4 call a method by method name
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 );

Method2 methobj = new method2 ();

Object Arglist [] = new object [2];

Arglist [0] = new INTEGER (37 );

Arglist [1] = new INTEGER (47 );

Object retobj

= Meth. Invoke (methobj, Arglist );

Integer retval = (integer) retobj;

System. Out. println (retval. intvalue ());

}

Catch (throwable e ){

System. Err. println (E );

}

}

}

We will carefully introduce the implementation of method calls.

First, declare a class method2, which has a method public int add (int A, int B ). Note that the method name 'add', the Data Type int of two form parameters, and the return value type Int. This information is very important for dynamically calling a class method.

The functions implemented in the main function are as follows:

1. Class CLS = Class. forname ("method2"): gets the class instance object Cls.

2. Class partypes [] = new class [2];

Partypes [0] = integer. type;

Partypes [1] = integer. type;

Declare an array of classes to save the Data Types of the two parameters.

3. Method meth = Cls. getmethod ("add", partypes); note that the getmethod method returns a matching method. The matching conditions are limited in two parts. One is the method name and the other is an array of parameter types of the method. (Because method Overloading is allowed in Java, the Data Type of the parameter must be described.) The order of each parameter type in the parameter type array must be the same as that in method declaration.

4. method2 methobj = new method2 (): declares an instance variable of the method2 class.

5. Object Arglist [] = new object [2];

Arglist [0] = new INTEGER (37 );

Arglist [1] = new INTEGER (47 );

Declare an object array to store two parameter instances.

6. Object retobj = meth. Invoke (methobj, Arglist): actually calls the Add function. Note the two parameters of method invoke (). methobj is an instance of the class that calls a method (or declares a method). Arglist is indeed called (here the add method is used, parameter instance array. The returned value is still the instance retobj of an object.

7. Integer retval = (integer) retobj;

System. Out. println (retval. intvalue (); converts the type of the returned object instance and outputs it.

3.5 generate a new instance
Import java. Lang. Reflect .*;


Public class constructor2 {

Public constructor2 ()

{

}


Public constructor2 (int A, int B)

{

System. Out. println (

"A =" + A + "B =" + B );

}


Public static void main (string ARGs [])

{

Try {

Class CLS = Class. forname ("constructor2 ");

Class partypes [] = new class [2];

Partypes [0] = integer. type;

Partypes [1] = integer. type;

Constructor CT

= Cls. getconstructor (partypes );

Object Arglist [] = new object [2];

Arglist [0] = new INTEGER (37 );

Arglist [1] = new INTEGER (47 );

Object retobj = CT. newinstance (Arglist );

}

Catch (throwable e ){

System. Err. println (E );

}

}

}

This example illustrates how to use the newinstancce () method of the constructor class. The specific process is similar to using the invoke () method in section 3.4.

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