Use Java Reflection

Source: Internet
Author: User

 

Reflection is one of the characteristics of the Java programming language. It allows running Java programs to check themselves, or "self-Review", and can directly operate on internal properties of the program. For example, you can use it to obtain and display the names of members in the Java class.

This capability of Java may not be used in many practical applications, but it does not exist in other programming languages. For example, Pascal, C, or C ++ cannot obtain information related to function definitions in the program.

JavaBean is one of the practical applications of reflection. It allows some tools to operate software components visually. These tools dynamically load and obtain the attributes of Java components (classes) through reflection.

A simple example

The following simple example shows how reflection works.

Import java. lang. reflect .*;

Public class DumpMethods {

Public static void main (String args []) {

Try {

Class c = Class. forName (args [0]);

Method m [] = c. getDeclaredMethods ();

For (int I = 0; I <m. length; I ++)

System. out. println (m [I]. toString ());

}

Catch (Throwable e ){

System. err. println (e );

}

}

}

Run the following statement:

Java DumpMethods java. util. Stack

The output result is as follows:

Public java. lang. Object java. util. Stack. push (java. lang. Object)

Public synchronized java. lang. Object java. util. Stack. pop ()

Public synchronized java. lang. Object java. util. Stack. peek ()

Public boolean java. util. Stack. empty ()

Public synchronized int java. util. Stack. search (java. lang. Object)

In this way, the names of java. util. Stack classes and their delimiters and return types are listed.

This program uses Class. forName to load the specified Class, and then calls getDeclaredMethods to obtain the list of methods defined in this Class. Java. lang. reflect. Methods is a class used to describe a single method in a class.

Start Using Reflection

The class used for reflection, such as Method, can be found in the java. lang. relfect package. When using these classes, you must follow three steps: the first step is to obtain the java. lang. Class Object of the Class you want to operate on. In the running Java program, java. lang. Class is used to describe classes and interfaces.

The following is one of the methods to obtain a Class object:

Class c = Class. forName ("java. lang. String ");

This statement gets a Class Object of the String class. Another method is as follows:

Class c = int. class;

Or

Class c = Integer. TYPE;

They can obtain information about classes of the basic type. The latter method accesses the pre-defined TYPE field in the encapsulation class of the basic TYPE (such as Integer.

The second step is to call methods such as getDeclaredMethods to obtain a list of all methods defined in this class.

Once this information is obtained, you can perform Step 3-use the reflection API to perform such operations, as shown in the following code:

Class c = Class. forName ("java. lang. String ");

Method m [] = c. getDeclaredMethods ();

System. out. println (m [0]. toString ());

It prints the prototype of the first method defined in String in text format.

In the example below, these three steps will provide examples for Using reflection to process special applications.

Simulate the instanceof Operator

After getting the Class information, the next step is to solve some basic problems about the Class object. For example, the Class. isInstance method can be used to simulate the instanceof OPERATOR:

Class {}

Public class instance1 {

Public static void main (String args [])

{

Try {

Class cls = Class. forName ("");

Boolean b1

= Cls. isInstance (new Integer (37 ));

System. out. println (b1 );

Boolean b2 = cls. isInstance (new ());

System. out. println (b2 );

}

Catch (Throwable e ){

System. err. println (e );

}

}

}

In this example, A Class Object of Class A is created, and then check whether some objects are instances of Class. Integer (37) is not, but new A () is.

Find the Class Method

Find out what methods are defined in a class, which is a very valuable and basic reflection usage. The following code implements this usage:

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 );

}

}

}

This program first obtains the description of the method1 class, and then calls getDeclaredMethods to obtain a series of Method objects, which respectively describe each Method defined in the class, includes the public method, protected method, package method, and private method. If you use getMethods in the program to replace getDeclaredMethods, you can also obtain information about the inherited methods.

After obtaining the Method object list, it is not difficult to display the parameter type, exception type, and return value type of these methods. Whether these types are basic or class types can be provided by the objects of the description class in order.

The output result is as follows:

Name = f1

Decl class = class method1

Param #0 class java. lang. Object

Param #1 int

Exc #0 class java. lang. NullPointerException

Return type = int

-----

Name = main

Decl class = class method1

Param #0 class [Ljava. lang. String;

Return type = void

-----

Get the constructor Information

The usage of the get class constructor is similar to that of the above method, for example:

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 );

}

}

}

In this example, information about the returned type is not obtained because the constructor does not return the type.

The result of this program running is:

Name = constructor1

Decl class = class constructor1

-----

Name = constructor1

Decl class = class constructor1

Param #0 int

Param #1 double

-----

Obtain the fields (fields) of the class)

It is also possible to find out which data fields are defined in a class. The following code is doing this:

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 ();
<

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.