Java reflection mechanism [method reflection]

Source: Internet
Author: User
Tags modifiers

Java reflection mechanism [method reflection]

then the previous Java Reflection Mechanism [field reflection], by invoking the SetName method of the person class, sets the value of the Name field of obj to "Callpersonsetnamemethod" to understand what method reflection . The sample code is simple and easy to understand.

You can see that Method.invoke () is not actually the reflection invocation logic that you implement, but is delegated to Sun.reflect.MethodAccessor to handle. The real reflection is to call Methodaccessor.invoke () to actually complete the reflection call. See the source code can be found in the Methodaccessor.invoke () method has a lot of cached-related variables, indicating that the reflection of method is very consumption performance.

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:2014-10-25
* 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.InvocationTargetException;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Modifier;


/**
* <description functions in a word>
* Reflection is the mapping of the various components in the Java class into the 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-25
* <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 ("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 ());
Callpersonsetnamemethod (P);
System.out.println (P.tostring ());
}

/** <description functions in a word>
* Use the SetName method of the person class to set the value of obj's Name field to "Callpersonsetnamemethod" to understand what method reflection <BR>
* 2014-10-26
* <detail description>
* @author qiuzhenping
* @param obj
* @throws Exception [Parameters description]
* @return void [return type description]
* @exception throws [Exception] [exception description]
* @see [Related classes#related methods#related properties]
*/
private static void Callpersonsetnamemethod (Object obj) throws Exception {
Method[] methods = Person.class.getMethods ();//Get all methods
for (Method m:methods) {
M.setaccessible (TRUE);//Violent reflexes
if (M.getname (). Equals ("SetName")) {
M.invoke (obj, "Callpersonsetnamemethod");//Set the value of obj's Name field to "Callpersonsetnamemethod"
/**
* Below is the Java method source code for the Invoke method
* You can see that Method.invoke () is not actually a reflection invocation logic that is implemented by itself, but is delegated to sun.reflect.MethodAccessor for processing.
* True reflection is called Methodaccessor.invoke () really completes the reflection call.
* See the source code can be found in the Methodaccessor.invoke () method There are many variables related to cached,
* Indicates that the reflection of method is very consuming performance
* Public object Invoke (Object obj, object ... args)
Throws Illegalaccessexception, IllegalArgumentException,
InvocationTargetException
{
if (!override) {
if (! Reflection.quickcheckmemberaccess (Clazz, modifiers)) {
Class caller = reflection.getcallerclass (1);
Class Targetclass = ((obj = = NULL | |! modifier.isprotected (modifiers))
? Clazz
: Obj.getclass ());

Boolean cached;
Synchronized (this) {
Cached = (Securitycheckcache = = caller)
&& (Securitychecktargetclasscache = = Targetclass);
}
if (!cached) {
Reflection.ensurememberaccess (caller, clazz, obj, modifiers);
Synchronized (this) {
Securitycheckcache = caller;
Securitychecktargetclasscache = Targetclass;
}
}
}
}
if (methodaccessor = = null) acquiremethodaccessor ();
return Methodaccessor.invoke (obj, args);
}
* */
}
}
}

/** <description functions in a word>
* Replace the character of type string in the Obj object with the characters in value containing I in 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);//Violent reflexes
if (f.gettype () = = String.class) {//byte-code comparison is used = =
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.) {
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]

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.