Java reflection mechanism implementation

Source: Internet
Author: User

Many mainstream frameworks use reflection technology. For example, the ssh framework uses two technologies: xml for configuration file + reflection.

Reflection-related class packages.

Java. lang. reflect. *; and java. lang. Class;

All types (including basic types) in Java correspond to a Class object, which is java. lang. Class. That is, for each type, there is a Class object in the Class that corresponds to it. Class has no public constructor. Note that there is no public access.

How to obtain Class objects

Copy codeThe Code is as follows:. For each object. getCalss (), you can obtain the corresponding Class.
. Class. forName (String), written in String: package name. Class name. The object corresponding to the package name. Class name will be created.
Note: 1.2 only applies to reference types
. For basic TYPE: encapsulation Class. TYPE represents the Class Object of the corresponding basic TYPE. Integer. TYPE corresponds to the Class Object of the int TYPE.
Note: 3 only applies to Basic Types
. Type, Class. <4th types are generic.>
The above four methods, only method 2 is dynamic, as long as you change a package, it has dynamic potential. So the true significance of dynamic programming can only use method 2.

There is only one Class object for each type, that is, they only have one address, but different types are different.

Therefore, the print result below is true.

Copy codeThe Code is as follows: // pair and reference type
Class c1 = "". getClass ();
Class c2 = Class. forName ("java. lang. String ");
Class c3 = String. class;
System. out. println (c1 = c2); // true
// For Basic Types
Class num1 = Integer. TYPE;
Class num2 = int. class;
System. out. println (num1 = num2); // true

Reflection methods used to obtain members of a class

[Obtain the structure <according to the parameter type>] (declared is generally used)

Copy codeThe Code is as follows: Constructor <T> getConstructor (Class <?>... ParameterTypes)
Returns a Constructor object that reflects the specified public Constructor of the Class Object.
Constructor <?> [] GetConstructors ()
Returns an array containing certain Constructor objects, which reflect all the common Constructor methods of the classes represented by this Class object.
Constructor <T> getDeclaredConstructor (Class <?>... ParameterTypes)
Returns a Constructor object that reflects the specified Constructor of the Class object or interface.
Constructor <?> [] GetDeclaredConstructors ()
Returns an array of Constructor objects that reflect all Constructor methods of Class declarations represented by this Class object.

[Obtain attributes <by attribute name>] (declared is generally used in use, because attributes are generally private)
Copy codeThe Code is as follows: Field getField (String name)
Returns a Field object that reflects the specified public member fields of the Class or interface represented by this Class object.
Field [] getFields ()
Returns an array containing some Field objects, which reflect all accessible public fields of the Class or interface represented by this Class object.
Field getDeclaredField (String name)
Returns a Field object that reflects the declared fields specified by the Class object or interface.
Field [] getDeclaredFields ()
Returns an array of the Field object. These objects reflect all fields declared by the Class object or interface.

[Obtain method <method name and parameter type>] (declared is generally used)Copy codeThe Code is as follows: Method getMethod (String name, Class <?>... ParameterTypes)
Returns a Method object that reflects the specified public member methods of the Class or interface represented by this Class object.
Method [] getMethods ()
Returns an array containing some Method objects, these objects reflect the public member methods of the classes or interfaces represented by this Class Object (including those declared by the Class or interface and those inherited from the superclass and superinterfaces.
Method getDeclaredMethod (String name, Class <?>... ParameterTypes)
Returns a Method object that reflects the declared methods specified by the Class object or interface.
Method [] getDeclaredMethods ()
Returns an array of Method objects. These objects reflect all the methods declared by the Class object or interface, including public, protected, default (Package) Access, and private methods, but does not include the inherited methods.
T newInstance ()
Creates a new instance of the Class represented by this Class object. <New Instance () can dynamically create objects>
String toString ()
Converts an object to a string.

Note:

New Instance () calls the construction without parameters. If the class does not have a construction method without parameters, newInstance () will produce an exception.

Methods With declared support private, but do not support inheritance. Methods without declared support inheritance. Private methods are not supported, and only public objects can be retrieved.

Therefore, the attribute is generally declared, because the attribute is generally private, and the method is generally not declared, and the structure is generally not declared.

Obtains the attributes and methods of the class through simulated instance reflection.

Assign values to attributes using reflection

Method in Field

Object get (Object obj)

Returns the value of the Field in the specified object.

Field f = c. getXXField (attribute name );

Value = f. get (object );

Void set (Object obj, Object value)

Set the Field represented by this Field object on the specified object variable to the specified new value.

F. set (object, value );

Class <?> GetType ()

Returns a Class object that identifies the declared type of the Field represented by this Field object.

This API is used to obtain the type of an attribute (Class Object is returned ).

Copy codeThe Code is as follows: Class c = Student. class;
Object obj = c. newInstance (); // create a Student Class Object
Field f = c. getDeclaredField ("name"); // get the name attribute
F. setAccessible (true); // set Private access.
F. set (obj, "zhangsan ");
System. out. println (f. get (obj); // obtain the value of the name attribute of obj.

Construct with reflection call

For constructing a real call, the newInstance () method is called.

Copy codeThe Code is as follows: Class c = Class. forName ("com. clazz. reflect. Student ");
Constructor con = c. getConstructor (); // no execution structure,
Object cObj = c. getConstructor (). newInstance (); // call the construction method without Parameters
Constructor conAll = c. getConstructor (int. class, String. class, int. class );
Object caobj = conAll. newInstance (1001, "zjamgs", 234235); // call the constructor with parameters.
System. out. println (caobj); // print the output

Call Methods Using Reflection

Object. Method Name (value: 1, 2, 3 );

Method m = c. getMethoed (Method name, parameter type ...);

M. invoke (object, method call parameter) if the shape parameter required by the underlying method is 0, the length of the provided args array can be 0 or null.

Copy codeThe Code is as follows: Class c = Class. forName ("com. clazz. reflect. Student ");
Object obj = c. newInstance (); // create a Sutdent Object.
Method msetName = c. getMethod ("setName", String. class); // obj does not need to be converted
MsetName. invoke (obj, "zhangsan"); // call the setName method and pass the parameter.
Method msetId = c. getMethod ("setId", int. class );
MsetId. invoke (obj, 409090202 );
System. out. println (obj );

Reflection application instance

Entity class

Copy codeThe Code is as follows: package org. dennisit. reflect. entity;
Import java. io. Serializable;
/**
*
* User. java
*
* @ Version: 1.1
*
* @ Author: su Ruian <a href = "mailto: DennisIT@163.com"> send mail </a>
*
* @ Since: 1.0 Creation Time: 01:43:56
*
* TODO: class User. java is used...
*
*/
Public class User implements Serializable {

Private String test;

Public void execute (String name, int age ){
System. out. println ("name =" + name + ", age =" + age );
}
}

Reflection TestingCopy codeThe Code is as follows: package org. dennisit. reflect. main;
Import java. lang. reflect. Field;
/**
*
* ReflectEx. java
*
* @ Version: 1.1
*
* @ Author: su Ruian <a href = "mailto: DennisIT@163.com"> send mail </a>
*
* @ Since: 1.0 Creation Time: 01:46:00
*
* TODO: class ReflectEx. java is used...
*
*/
Public class ReflectEx {

Public static void main (String [] args) throws Exception {
Class cls = Class. forName ("org. dennisit. reflect. entity. User ");
Object obj = cls. newInstance (); // create a User Object
Field f = cls. getDeclaredField ("test"); // obtain the test attribute.
F. setAccessible (true); // open the access permission of the private property test
F. set (obj, "zhangsan"); // re-copy for test
System. out. println (f. get (obj); // obtain the test attribute value of obj.
// Obtain the method based on the method name execute
Java. lang. reflect. Method m = cls. getMethod ("execute", String. class, int. class );
M. invoke (obj, "dennisit", 23); // call the execute Method
}
}

Running EffectCopy codeThe Code is as follows: zhangsan
Name = dennisit, age = 23

Compile an example of reflecting the dynamic instantiation classCopy codeThe Code is as follows: package org. dennisit. reflect. main;
Import java. lang. reflect. Field;
Import java. lang. reflect. Method;
Import java. util. Map;
Import java. util. Set;
/**
*
* DynamicReflect. java
*
* @ Version: 1.1
*
* @ Author: su Ruian <a href = "mailto: DennisIT@163.com"> send mail </a>
*
* @ Since: 1.0 Creation Time: 01:58:12
*
* TODO: An Example of dynamic instantiation Using Reflection
*
*/
Public class DynamicReflect {

Public static Object getInstance (String className, Map <String, Object> map) throws Exception {
Class c = Class. forName (className );
Object obj = c. newInstance (); // Object
Set <String> keys = map. keySet (); // obtain all the corresponding attributes.
Field [] fAll = c. getDeclaredFields (); // obtain all attributes of the class
For (int I = 0; I <fAll. length; I ++ ){
For (String key: keys) {// loop matching
If (fAll [I]. getName (). equals (key) {// if the property passed in by the user matches the property name in the obtained class
Field f = c. getDeclaredField (key); // get this attribute
// Construct the setXxx () method name
String methodName = "set" + key. substring (0, 1). toUpperCase () + key. substring (1 );
Method method = c. getMethod (methodName, f. getType (); // obtain the corresponding Method based on the constructed User Name
Method. invoke (obj, map. get (key); // method call
} Else {
Continue;
}
}
}
Return obj;
}
}

Next we will test the example of dynamic reflection instantiation.

Entity class

Copy codeThe Code is as follows: package org. dennisit. reflect. entity;
Import java. io. Serializable;
/**
*
* User. java
*
* @ Version: 1.1
*
* @ Author: su Ruian <a href = "mailto: DennisIT@163.com"> send mail </a>
*
* @ Since: 1.0 Creation Time: 01:43:56
*
* TODO: entity class
*
*/
Public class User implements Serializable {

Private String name;
Private int age;
Private String email;

Public User () {// there must be no parameter construction

}

// Getter () and setter ()

}

Main test classCopy codeThe Code is as follows: package org. dennisit. reflect. main;
Import java. util. HashMap;
Import java. util. Map;
Import org. dennisit. reflect. entity. User;
/**
*
* ReflectEx. java
*
* @ Version: 1.1
*
* @ Author: su Ruian <a href = "mailto: DennisIT@163.com"> send mail </a>
*
* @ Since: 1.0 Creation Time: 01:46:00
*
* TODO: class ReflectEx. java is used...
*
*/
Public class ReflectEx {

Public static void main (String [] args) throws Exception {
Class cls = Class. forName ("org. dennisit. reflect. entity. User ");
String className = "org. dennisit. reflect. entity. User ";
Map <String, Object> map = new HashMap <String, Object> ();
Map. put ("name", "dennisit ");
Map. put ("age", 22 );
Map. put ("email", "dennisit@163.com ");

User user = (User) DynamicReflect. getInstance (className, map );
System. out. println (user. getName () + "," + user. getAge () + "," + user. getEmail ());
}
}

Program running resultCopy codeCode: dennisit, 22, dennisit@163.com

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.