A brief analysis of Java reflection mechanism

Source: Internet
Author: User
Tags locale

Ext.: http://www.cnblogs.com/gulvzhe/archive/2012/01/27/2330001.html

————————————————————————————————————————————————

Java reflection mechanism is in the running state, for any class , can know all the properties and methods of this class, for any one object , can call any of its methods and properties This dynamic acquisition of information and the ability to dynamically invoke the object's methods is called the reflection mechanism of the Java language. The concept of reflection was first proposed by Smith in 1982, and was primarily a capability for a program to access, detect, and modify its own state or behavior. The proposal of this concept soon triggered the research on the application of reflectivity in Computer science field. It is first used in the field of programming language design, and has achieved achievements in Lisp and object-oriented. Of course, reflection itself is not a new concept, it may remind us of the concept of reflection in optics, although computer science gives a new meaning to the concept of reflection, but, in fact, they do have some similarities, which helps us understand.

The Java reflection mechanism mainly provides the following purposes:

    • Determine the class to which any object belongs at run time
    • To construct an object of any class at run time
    • Determine the member variables and methods that any one class has at run time
    • Methods to invoke any object at run time

Let's look at a simple example to understand how the reflection mechanism works in Java.

Package com.wanggc.reflection;

Import Java.lang.reflect.Method;

/**
* Java reflection exercises.
*
* @author WANGGC
*/
public class Fornametest {

/**
* Entry function.
*
* @param args
* Parameters
* @throws Exception
* Error message
*/
public static void Main (string[] args) throws Exception {
Get class
Class<?> cls = Class.forName (Args[0]);
Method of obtaining the corresponding object through class
Method[] methods = Cls.getmethods ();
Output each method name
for (Method method:methods) {
System.out.println (method);
}
}
}

When the passed-in parameter is java.lang.String, the following result is output

public boolean java.lang.String.equals (Java.lang.Object)
Public java.lang.String java.lang.String.toString ()
public int Java.lang.String.hashCode ()
public int Java.lang.String.compareTo (java.lang.String)
public int Java.lang.String.compareTo (java.lang.Object)
public int java.lang.String.indexOf (int)
public int java.lang.String.indexOf (int,int)
public int java.lang.String.indexOf (java.lang.String)
public int java.lang.String.indexOf (java.lang.string,int)
public static java.lang.String java.lang.String.valueOf (int)
public static java.lang.String java.lang.String.valueOf (char)
public static Java.lang.String Java.lang.String.valueOf (Boolean)
public static java.lang.String java.lang.String.valueOf (float)
public static java.lang.String java.lang.String.valueOf (Char[],int,int)
public static java.lang.String java.lang.String.valueOf (double)
public static java.lang.String java.lang.String.valueOf (char[])
public static java.lang.String java.lang.String.valueOf (Java.lang.Object)
public static java.lang.String java.lang.String.valueOf (Long)
public char java.lang.String.charAt (int)
public int java.lang.String.codePointAt (int)
public int Java.lang.String.codePointBefore (int)
public int Java.lang.String.codePointCount (int,int)
public int java.lang.String.compareToIgnoreCase (java.lang.String)
Public java.lang.String Java.lang.String.concat (java.lang.String)
public boolean java.lang.String.contains (java.lang.CharSequence)
public boolean java.lang.String.contentEquals (java.lang.CharSequence)
public boolean java.lang.String.contentEquals (Java.lang.StringBuffer)
public static java.lang.String java.lang.String.copyValueOf (char[])
public static java.lang.String java.lang.String.copyValueOf (Char[],int,int)
public boolean java.lang.String.endsWith (java.lang.String)
public boolean java.lang.String.equalsIgnoreCase (java.lang.String)
public static java.lang.String Java.lang.String.format (java.lang.string,java.lang.object[])
public static java.lang.String Java.lang.String.format (java.util.locale,java.lang.string,java.lang.object[])
Public byte[] Java.lang.String.getBytes (java.lang.String) throws Java.io.UnsupportedEncodingException
public void Java.lang.String.getBytes (Int,int,byte[],int)
Public byte[] Java.lang.String.getBytes ()
Public byte[] Java.lang.String.getBytes (java.nio.charset.Charset)
public void Java.lang.String.getChars (Int,int,char[],int)
Public native java.lang.String Java.lang.String.intern ()
public boolean java.lang.String.isEmpty ()
public int java.lang.String.lastIndexOf (java.lang.String)
public int java.lang.String.lastIndexOf (int,int)
public int java.lang.String.lastIndexOf (int)
public int java.lang.String.lastIndexOf (java.lang.string,int)
public int java.lang.String.length ()
public boolean java.lang.String.matches (java.lang.String)
public int java.lang.String.offsetByCodePoints (int,int)
public boolean java.lang.String.regionMatches (Boolean,int,java.lang.string,int,int)
public boolean java.lang.String.regionMatches (Int,java.lang.string,int,int)
Public java.lang.String java.lang.String.replace (java.lang.charsequence,java.lang.charsequence)
Public java.lang.String java.lang.String.replace (Char,char)
Public java.lang.String java.lang.String.replaceAll (java.lang.string,java.lang.string)
Public java.lang.String Java.lang.String.replaceFirst (java.lang.string,java.lang.string)
Public java.lang.string[] Java.lang.String.split (java.lang.String)
Public java.lang.string[] Java.lang.String.split (java.lang.string,int)
public boolean java.lang.String.startsWith (java.lang.String)
public boolean java.lang.String.startsWith (Java.lang.string,int)
Public java.lang.CharSequence java.lang.String.subSequence (int,int)
Public java.lang.String java.lang.String.substring (int)
Public java.lang.String java.lang.String.substring (int,int)
Public char[] Java.lang.String.toCharArray ()
Public java.lang.String java.lang.String.toLowerCase ()
Public java.lang.String java.lang.String.toLowerCase (Java.util.Locale)
Public java.lang.String java.lang.String.toUpperCase ()
Public java.lang.String java.lang.String.toUpperCase (Java.util.Locale)
Public java.lang.String Java.lang.String.trim ()
Public final native void Java.lang.Object.wait (long) throws Java.lang.InterruptedException
Public final void Java.lang.Object.wait () throws Java.lang.InterruptedException
Public final void Java.lang.Object.wait (Long,int) throws Java.lang.InterruptedException
Public final native Java.lang.Class Java.lang.Object.getClass ()
Public final native void Java.lang.Object.notify ()
Public final native void Java.lang.Object.notifyAll ()

This lists all the method names, their qualifiers, return types, and exceptions thrown by the Java.lang.String class. This program loads the specified class using the class Forname method, and then calls the GetMethods method to return the list of methods for the specified class. Java.lang.reflect.Method is used to describe a single method in a class.

Using the reflection mechanism of Java, it is generally necessary to follow three steps:

      1. Get the class object you want to manipulate
      2. The class object obtained by the first step gets the method or property name of the operation
      3. The method or property obtained in the second step of the operation

When Java runs, a class, regardless of how many objects are generated, will correspond to the same class object, which represents the classes and interfaces in the program that are running. There are three ways to get the class object for the action classes:

      1. Call the static method of class forname, as in the example above;
      2. Use the class's. class syntax, such as:class<?> cls = String.class;
      3. Call the GetClass method of the object, such as: String str = "ABC";class<?> CLS = str. getclass ();

Here's an example of how to execute a method of an object through the three steps you've previously complained about:

 package com.wanggc.reflection; 
2
3 import Java.lang.reflect.Method;
4
5/**
6 * Java reflection exercise.
7 *
8 * @author WANGGC
9 */
public class Reflectiontest {
One public static void main (string[ ] args) throws Exception {
Display display = new display ();
13//Get Class
class<?> cls = Display.getclass ();
15//Get the Show method of display class by class
methods = Cls.getmethod ("show", String.class);
17//Call the Show Method
Method.invoke (DisPlay, "WANGGC");

+}

class DisPlay {
* public void Show (String name) {
System.out.println (" Hello: "+ name");
25}

As mentioned earlier, each class of a Java program has a class object corresponding to it. The first step in Java reflection is to get the class object, such as the code 14 line. Of course, the methods of each class must also have a method object corresponding to it. To call this method by reflection, you first get the method object for this approach, such as the code 16 line, and then use the method object in turn to call it, such as code 18 lines. Note the first parameter of the 16-line GetMethod method is the method name, the second is the parameter type of this method, and if it is multiple arguments, then add the parameter, because GetMethod is a mutable parameter method. The Invoke method that executes 18 lines of code is actually executing the show method, noting that the first parameter of invoke is an object of the display class, which is the show method that invokes which object of the display class, and the second parameter is the parameter passed to the Show method. The type and number must be the GetMethod method with 16 rows always.

The previous example describes how to invoke a method of a class through reflection, and then an instance that tells you how to assign a value by reflection to a property of a class:

Package com.wanggc.reflection;

Import Java.lang.reflect.Field;

/**
* Properties of Java reflection practice.
*
* @author WANGGC
*/
public class Reflectiontest {
public static void Main (string[] args) throws Exc eption {
//Build Student object
Student Student = new Student ();
//Assign value to student object
Student.setstuname ("WANGGC");
Student.s Etstuage (24);
//Create Copy target object
Student deststudent = new Student ();
//Copy Student Object
Copybean (Student, deststudent);
/Output copy result br> System.out.println (Deststudent.getstuname () + ":"
+ deststudent.getstuage ());
}

/**
* Copy Student object information.
*
* @param from
* Copy Source Object
* @param dest
* Copy target Object
* @throws Exception
* Exceptions
*/
private static void Copybean (object from, Object dest) throws Exception {
Gets the class object of the Copy source object
class<?> Fromclass = From.getclass ();
Gets the list of properties of the copy source object
field[] Fromfields = Fromclass.getdeclaredfields ();
Gets the class object that copies the target object
class<?> Destclass = Dest.getclass ();
Field Destfield = null;
for (Field fromfield:fromfields) {
Gets the property name of the copy source object
String name = Fromfield.getname ();
Gets the property that copies the same name of the target object
Destfield = Destclass.getdeclaredfield (name);
To set the accessibility of a property
Fromfield.setaccessible (TRUE);
Destfield.setaccessible (TRUE);
Assigns the value of the property of the copy source object to the corresponding property of the Copy target object
Destfield.set (dest, Fromfield.get (from));
}
}
}

/**
* Student class.
*/
Class Student {
/** Name * *
Private String Stuname;
/** Age */
private int stuage;

/**
* Get the student's name.
*
* @return Student Name
*/
Public String Getstuname () {
return stuname;
}

/**
* Set Student's name
*
* @param stuname
* Student Name
*/
public void Setstuname (String stuname) {
This.stuname = Stuname;
}

/**
* Get student Age
*
* @return Student Age
*/
public int getstuage () {
return stuage;
}

/**
* Set student Age
*
* @param stuage
* Student Age
*/
public void setstuage (int stuage) {
This.stuage = Stuage;
}
}

Java's launch mechanism classes have class counterparts, class methods have method corresponding, of course, the attribute also has field and corresponding. The comments in the code have been commented out in detail and will not be mentioned here. Note, however, that field provides the get and set methods for getting and setting the value of the property, but because the property is private, you need to set the accessibility of the property to true, such as the Code 50~51 line. You can also set accessibility for the entire fields, using AccessibleObject's static method setaccessible under 40 rows, such as: Accessibleobject.setaccessible (Fromfields, true);

The previous section describes how to manipulate the methods and properties of a class with the Java reflection mechanism, and then an example that describes how to create an object of a class at run time:

Package com.wanggc.reflection;

Import Java.lang.reflect.Field;

/**
* Java Reflection Properties exercises.
*
* @author WANGGC
*/
public class Reflectiontest {
public static void Main (string[] args) throws Exception {
Set up Student objects
Student Student = new Student ();
Assigning values to student objects
Student.setstuname ("WANGGC");
Student.setstuage (24);
Creating a Copy target object
Student deststudent = (Student) Copybean (Student);
Output Copy Results
System.out.println (Deststudent.getstuname () + ":"
+ deststudent.getstuage ());
}

/**
* Copy Student object information.
*
* @param from
* Copy Source Object
* @param dest
* Copy target Object
* @throws Exception
* Exceptions
*/
Private static Object Copybean (object from) throws Exception {
Gets the class object of the Copy source object
class<?> Fromclass = From.getclass ();
Gets the list of properties of the copy source object
field[] Fromfields = Fromclass.getdeclaredfields ();
Gets the class object that copies the target object
Object ints = Fromclass.newinstance ();
for (Field fromfield:fromfields) {
To set the accessibility of a property
Fromfield.setaccessible (TRUE);
Assigns the value of the property of the copy source object to the corresponding property of the Copy target object
Fromfield.set (INTs, Fromfield.get (from));
}

return ints;
}
}

/**
* Student class.
*/
Class Student {
/** Name * *
Private String Stuname;
/** Age */
private int stuage;

/**
* Get the student's name.
*
* @return Student Name
*/
Public String Getstuname () {
return stuname;
}

/**
* Set Student's name
*
* @param stuname
* Student Name
*/
public void Setstuname (String stuname) {
This.stuname = Stuname;
}

/**
* Get student Age
*
* @return Student Age
*/
public int getstuage () {
return stuage;
}

/**
* Set student Age
*
* @param stuage
* Student Age
*/
public void setstuage (int stuage) {
This.stuage = Stuage;
}
}

This example runs the same result as the previous example. However, the object returned by the Copybean method is no longer passed out, but is generated internally by the method, as shown in the 40th line of code. Note: class's Newinstance method can only be used to create classes that contain only parameterless constructors, and if a class has only constructors with parameters, use another way: Fromclass.getdeclaredconstructor ( Int.class,string.class). newinstance ("WANGGC");

At this point, the common functions of the Java Reflection mechanism (the method of invoking objects at runtime, the use of class properties, the object of a class) have been introduced.

Add: There are two methods for getxxx and getgetdeclaredxxx when obtaining methods, properties, and constructors for a class. The difference is that the former returns methods and properties that have access to public, including those in the parent class, but the latter returns all the methods and properties of the access permission, excluding the parent class.

A brief analysis of Java reflection mechanism

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.