Java reflection mechanism [Field reflection], java Mechanism field reflection

Source: Internet
Author: User

Java reflection mechanism [Field reflection], java Mechanism field reflection
Java reflection mechanism [Field reflection]1. Concepts and functions of reflection

Reflection maps various components in the Java class into corresponding Java classes. For example, a Java Class is represented by a Class Object. The components of a class are divided into member variables, methods, constructor methods, packages, and so on.

The Java reflection mechanism mainly provides the following functions: to judge the class to which any object belongs at runtime; to construct the object of any class at runtime; judge the member variables and methods of any class at runtime; call the methods of any object at runtime; generate a dynamic proxy.

2. Field reflection

The following code replaces the characters containing I in the Value corresponding to the String type field in the obj object with abc. This simple case is used to preliminarily analyze the reflection mechanism of Java.

Java Code

/*

* System Abbrev:

* System Name:

* Component No:

* Component Name:

* File name: ReflectTestMain. java

* Author: Qiuzhenping

* Date: 2014-10-25

* Description: <description>

*/

 

/* Updation record 1:

* Updation date:

* Updator: Qiuzhenping

* Trace No: <Trace No>

* Updation No: <Updation No>

* Updation Content: <List all contents of updation and all methods updated.>

*/

Package com. qiuzhping. reflect. main;

 

Import java. lang. reflect. Constructor;

Import java. lang. reflect. Field;

Import java. lang. reflect. Method;

 

/**

* <Description functions in a word>

* Reflection maps various components in the Java class into corresponding Java classes.

* <Detail description>

*

* @ Author Qiuzhenping

* @ Version [Version NO, 2014-10-25]

* @ See [Related classes/methods]

* @ Since [product/module version]

*/

Public class ReflectTestMain {

 

/** <Default constructor>

*/

Public ReflectTestMain (){

// TODO Auto-generated constructor stub

}

 

/** <Description functions in a word>

* 2014-10-

* <Detail description>

* @ Author Qiuzhenping

* @ Param args [Parameters description]

* @ Return void [Return type description]

* @ Exception throws [Exception] [Exception description]

* @ See [Related classes # Related methods # Related properties]

*/

Public static void main (String [] args) throws Exception {

// TODO Auto-generated method stub

// Constructor [] contructor = Person. class. getConstructors ();

// Method [] method = Person. class. getMethods ();

Person p = new Person (24, "Qiuzhping", "100001", "Qiuzhping ");

// Field [] field = p. getClass (). getDeclaredFields ();

// For (Field f: field ){

// F. setAccessible (true );

// System. out. println (f. getName ());

// Object obj = f. get (p );

// System. out. println (obj );

//}

ChangeStringValue (p );

System. out. println (p. toString ());

}

 

/** <Description functions in a word>

* Replace the characters containing I in the Value corresponding to the String type field in the obj object with abc. <BR>

* 2014-10-26

* <Detail description>

* @ Author Qiuzhenping

* @ Param obj [Parameters description]

* @ Return void [Return type description]

* @ Exception throws [Exception] [Exception description]

* @ See [Related classes # Related methods # Related properties]

*/

Private static void changeStringValue (Object obj) throws Exception {

Field [] fields = obj. getClass (). getDeclaredFields ();

For (Field f: fields ){

F. setAccessible (true); // brute force reflection

If (f. getType () = String. class) {// use = to compare bytecode

String oldValue = (String) f. get (obj );

String newValue = oldValue. replaceAll ("I", "abc"); // replace all I with abc

F. set (obj, newValue );

}

}

}

Static class Person {

 

Public Person (int age, String name, String id, String pwd ){

Super ();

This. age = age;

This. name = name;

This. id = id;

This. pwd = pwd;

}

@ Override

Public String toString (){

Return "age =" + age + "\ tname =" + name + "\ tid =" + id + "\ tpwd =" + pwd;

}

Private int age;

Private String name;

Private String id;

Private String pwd;

Public int getAge (){

Return age;

}

Public void setAge (int age ){

This. age = age;

}

Public String getName (){

Return name;

}

Public void setName (String name ){

This. name = name;

}

Public String getId (){

Return id;

}

Public void setId (String id ){

This. id = id;

}

Public String getPwd (){

Return pwd;

}

Public void setPwd (String pwd ){

This. pwd = pwd;

}

/** <Default constructor>

*/

Public Person (){

// TODO Auto-generated constructor stub

}

 

}

}

 

Java reflection mechanism [Method reflection]



Implementation principle of java reflection mechanism

Reflection mechanism: the so-called reflection mechanism is that the java language has a self-view capability during runtime. With this capability, You can thoroughly understand your situation and prepare for the next step. The following describes the reflection mechanism of java. Here you will subvert the original understanding of java.
The implementation of the Java reflection mechanism involves four classes: class, Constructor, Field, and Method. The class represents the time class Object and Constructor-class Constructor object, attribute object of Field-class, Method object of Method-class. Through these four objects, we can roughly see each group part of a class.

Class: when the program is running, the java runtime system processes all objects in the runtime. This information records the class to which each object belongs. virtual machines usually use the correct method for running type information (from: White Paper ). But how can we get this information? We need to use class objects. The getClass () method is defined in the Object class. We can use this method to obtain the Class Object of the specified object. Then we can analyze this object to get the information we want.

For example, ArrayList arrayList;

Class clazz = arrayList. getClass ();

Then I will process this object clazz.

Of course, the Class has many methods. Here we will focus on the methods related to the Constructor, Field, and Method classes.

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. This Java capability may not be used in many practical applications, but I personally think it should be mastered to have a deeper understanding of java.

1. Detection class:

Reflection's Working Mechanism

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

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.

Main Methods in Java class reflection

Java. lang. Class provides four independent reflection calls for any of the following three components: constructor, field, and method to obtain information in different ways. All calls follow a standard format. The following is a set of reflection calls used to find constructors:

Constructor getConstructor (Class [] params) -- obtains a common Constructor that uses special parameter types,

Constructor [] getConstructors () -- obtain all public constructors of the class

Constructor getDe ...... remaining full text>

Java: describes the function of the reflection mechanism? How many reflection applications are involved?

Fully explained: JAVA reflection mechanism
The JAVA reflection mechanism is in the running state. For any class, all attributes and methods of this class can be known; for any object, any method of this class can be called; this kind of dynamically obtained information and the function of dynamically calling object methods is called the reflection mechanism of java language.
The Java reflection mechanism mainly provides the following functions: to judge the class to which any object belongs at runtime; to construct the object of any class at runtime; judge the member variables and methods of any class at runtime; call the methods of any object at runtime; generate a dynamic proxy.
1. Get the attributes of an object

1 public Object getProperty (Object owner, String fieldName) throws Exception {
2 Class ownerClass = owner. getClass ();
3
4 Field field = ownerClass. getField (fieldName );
5
6 Object property = field. get (owner );
7
8 return property;
9}
Class ownerClass = owner. getClass (): obtains the Class of the object.

Field field = ownerClass. getField (fieldName): obtains the attribute declared by the Class through the Class.

Object property = field. get (owner): obtains the instance of this attribute through the Object. If this attribute is not public, IllegalAccessException is reported here.

2. Obtain the static attributes of a class.

1 public Object getStaticProperty (String className, String fieldName)
2 throws Exception {
3 Class ownerClass = Class. forName (className );
4
5 Field field = ownerClass. getField (fieldName );
6
7 Object property = field. get (ownerClass );
8
9 return property;
10}

Class ownerClass = Class. forName (className): first obtain the Class of this Class.

Field field = ownerClass. getField (fieldName): Same as above, get the attribute declared by Class through Class.

Object property = field. get (ownerClass): This is somewhat different from the above. Because this property is static, it is directly retrieved from the Class of the Class.

3. Execute the method of an object

1 public Object invokeMethod (Object owner, String methodName, Object [] args) throws Exception {
2
3 Class ownerClass = owner. getClass ();
4
5 Class [] argsClass = new Class [args. length];
6
7 for (int I = 0, j = args. length; I <j; I ++ ){
8 arg ...... remaining full text>

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.