Implementation of Java reflection mechanism _java

Source: Internet
Author: User
Tags array length inheritance object object reflection

Reflective technology is used in many mainstream frameworks. Like the SSH framework, two technical XML files are used to do the configuration file + reflection technology.


The class package that is associated with reflection.

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


All types (including basic types) in Java correspond to a class object, and this class is java.lang.Class. That is, each type has a class object in class that corresponds to it. class has no public constructor method. Attention is not no, there is no public.


How to get a class object

Copy Code code as follows:

. For each object. GETCALSS (), you can get the corresponding class.
. Class.forName (String), String: Package name. class name. The name of the package. The object that corresponds to the class name
Note: 1.2 Applies only to reference types
. For basic types: encapsulation classes. Type represents a class object of the corresponding base type. integer.type corresponds to the class object of int
Note: 3 applies only to basic types
. type, Class. < The 4th is the Universal .>
Of the above 4 methods, only method 2 is dynamic, just change a package on it. It has dynamic potential. So the real meaning of want to embody dynamic programming can only use Method 2.

Each type of class object has only one, that is, they have only one address, but different types are different.

So the following print results are true.

Copy Code code as follows:

Pairs and reference types
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 get members in a classThe relevant methods

[ get constructs < by parameter type ] ( usually with declared )

Copy Code code as follows:

Constructor<t> GetConstructor (class<?>. parametertypes)
Returns a constructor object that reflects the specified public constructor method for the class represented by this class object.
Constructor<?>[] GetConstructors ()
Returns an array of some constructor objects that reflect all the public constructor methods of the class represented by this class object.
Constructor<t> Getdeclaredconstructor (class<?>. parametertypes)
Returns an constructor object that reflects the specified construction method of the class or interface represented by this class object.
Constructor<?>[] Getdeclaredconstructors ()
Returns an array of constructor objects that reflect all the constructed methods of the class declaration represented by this class object.

[Get Properties<Based on the property name"] (It is usually used withDeclaredOf,Because properties are generally private)
Copy Code code as follows:

Field GetField (String name)
Returns a Field object that reflects the specified public member field of the class or interface represented by this class object.
Field[] GetFields ()
Returns an array containing some field objects that 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 specified declared field of the class or interface represented by this class object.
Field[] Getdeclaredfields ()
Returns an array of field objects that reflect all the fields declared by the class or interface represented by this class object.

[Get method < method name plus parameter type] (generally used with no declared)
Copy Code code 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 of some method objects that reflect the public member methods of the class or interface represented by this class object, including those declared by that class or interface, and those inherited from superclass and hyper interfaces.
Method Getdeclaredmethod (String name, Class<?> ... parametertypes)
Returns a method object that reflects the specified declared methods of the class or interface represented by this class object.
Method[] Getdeclaredmethods ()
Returns an array of method objects that reflect all the methods declared by the class or interface represented by this class object, including public, protection, default (package) access, and private methods, but excluding 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:

The new Instance () invokes the parameterless construct, and newinstance () generates an exception if the class does not have a parameterless constructor.

The declared approach is to support private, but does not support inheritance, no declared method supports inheritance, does not support private, and can only take out public things.

Therefore takes the attribute the time generally is takes the declared, because the attribute generally is the private, takes the method generally is does not take the declared, takes constructs generally also does not take the declared.

The related properties and methods in the instance simulation reflection fetching class

Using reflection to assign values to properties

Methods in field

Object get (Object obj)

Returns the value of the field represented by this field on the specified object.

Field f = C.getxxfield (property name);

Value = F.get (object);

void set (Object obj, Object value)

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

is used to get the type of the property (the Return class object).

Copy Code code as follows:

Class C = student.class;
Object obj = c.newinstance (); To create an object of the student class
Field f = C.getdeclaredfield ("name"); Get the Name property
F.setaccessible (TRUE); Setting private can be accessed.
F.set (obj, "Zhangsan");
System.out.println (F.get (obj)); Gets the value of the Name property of obj.

using reflection to invoke construction

For a constructed real call is when the Newinstance () method is invoked.

Copy Code code as follows:

Class C = class.forname ("com.clazz.reflect.Student");
Constructor con = C.getconstructor (); Construction is not performed,
Object CObj = C.getconstructor (). newinstance ()//Calling parameterless construction method
Constructor Conall = C.getconstructor (Int.class,string.class,int.class);
Object caobj = conall.newinstance (1001, "Zjamgs", 234235);//Call the constructor method with the parameter.
System.out.println (Caobj); Print output

invoking methods with reflection

Object. Method name (value 1,2,3);

Methods M = c.getmethoed (method name, parameter type ...);

M.invoke (object, parameter of method call) If the underlying method requires a shape parameter of 0, the supplied args array length can be 0 or null.

Copy Code code as follows:

Class C = class.forname ("com.clazz.reflect.Student");
Object obj = c.newinstance (); Creates a Sutdent object.
Method msetname = C.getmethod ("SetName", string.class);//obj No conversion type
Msetname.invoke (obj, "Zhangsan");//Call Method SetName, and pass parameters.
Method Msetid = C.getmethod ("SetId", Int.class);
Msetid.invoke (obj, 409090202);
System.out.println (obj);

Reflection Application Example

Entity classes

Copy Code code as follows:

Package org.dennisit.reflect.entity;
Import java.io.Serializable;
/**
*
* User.java
*
* @version: 1.1
*
* @author: Sujonin <a href= "mailto:dennisit@163.com" > Send mail </a>
*
* @since: 1.0 Date Created: 2013-2-26 01:43:56
*
* Todo:class User.java is used for ...
*
*/
public class User implements serializable{

Private String test;

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


Reflection Test Class
Copy Code code as follows:

Package org.dennisit.reflect.main;
Import Java.lang.reflect.Field;
/**
*
* Reflectex.java
*
* @version: 1.1
*
* @author: Sujonin <a href= "mailto:dennisit@163.com" > Send mail </a>
*
* @since: 1.0 Date Created: 2013-2-26 01:46:00
*
* Todo:class Reflectex.java is used for ...
*
*/
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 object for user
Field f = Cls.getdeclaredfield ("test"); Get the Test property
F.setaccessible (TRUE); To open the access rights for the private property test
F.set (obj, "Zhangsan"); Re-replicate for test
System.out.println (F.get (obj)); Get the test property value for obj
Execute Fetch method based on method name
Java.lang.reflect.Method m = Cls.getmethod ("Execute", String.class, Int.class);
M.invoke (obj, "dennisit", 23); Calling the Execute method
}
}


Run effect
Copy Code code as follows:

Zhangsan
Name=dennisit,age=23

Write an example of a reflection dynamic instantiation class
Copy Code code 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: Sujonin <a href= "mailto:dennisit@163.com" > Send mail </a>
*
* @since: 1.0 Date Created: 2013-2-26 01:58:12
*
* TODO: Examples 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 Object
set<string> keys = Map.keyset (); Get all of the corresponding properties
field[] FAll = C.getdeclaredfields (); Get all the properties in a class
for (int i=0;i<fall.length;i++) {
for (String Key:keys) {//Loop match
if (Fall[i].getname (). Equals (key)) {//If the property passed in by the user matches the property name in the acquired class
Field f = C.getdeclaredfield (key);//Get this property
Building Setxxx () method name
String methodname = "Set" + key.substring (0,1). toUpperCase () +key.substring (1);
Method methods = C.getmethod (methodname, F.gettype ());//Get the corresponding way based on the user name you built
Method.invoke (obj, Map.get (key));//Method call
}else{
Continue
}
}
}
return obj;
}
}


Next we test the dynamic reflection instantiation example we wrote

Entity classes

Copy Code code as follows:

Package org.dennisit.reflect.entity;
Import java.io.Serializable;
/**
*
* User.java
*
* @version: 1.1
*
* @author: Sujonin <a href= "mailto:dennisit@163.com" > Send mail </a>
*
* @since: 1.0 Date Created: 2013-2-26 01:43:56
*
* TODO: Entity classes
*
*/
public class User implements serializable{

private String name;
private int age;
Private String Email;

Public User () {//must have a parameterless construct

}

Getter () and setter ()

}


Main test class
Copy Code code 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: Sujonin <a href= "mailto:dennisit@163.com" > Send mail </a>
*
* @since: 1.0 Date Created: 2013-2-26 01:46:00
*
* Todo:class Reflectex.java is used for ...
*
*/
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 Run Results
Copy Code code as follows:

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.