24th Part _java Reflection detailed

Source: Internet
Author: User
Tags modifiers object object

The reflection mechanism of the Java language

In the Java Runtime environment, for any class, can you know what the properties and methods of this class are? Can any one of its methods be called for any of the objects? The answer is yes. This dynamic acquisition of information for classes and the ability to dynamically invoke objects is derived from the Java language's reflection (Reflection) mechanism.

The Java reflection mechanism mainly provides the following functions

    • Determine the class to which any object belongs at run time.
    • Constructs an object of any class at run time.
    • At run time, determine the member variables and methods that any one class has.
    • A method that invokes any object at run time.

reflection is a key property of Java as a dynamic (or quasi-dynamic) language. This mechanism allows the program to obtain the internal information of any given class with a known name through the reflection APIs at runtime. includes its modifiers (such as public, static, and so on), superclass (such as object), interfaces implemented (such as Serializable), It also includes all information about its fields and methods, and can change the fields content or call methods at run time.

In General, the developer community speaks of dynamic language, which is broadly agreed to as "when a program is run, it allows you to change the program structure or variable type, which is called Dynamic language." from this point of view, Perl,python,ruby is a dynamic language, and c++,java,c# is not a dynamic language. Although Java is not a dynamic language under such definitions and classifications, it has a very prominent dynamic correlation mechanism: Reflection. The meaning of this word is: reflection, image, reflection, used in Java refers to we can at runtime loading, detection, using the classes is completely unknown during compilation. In other words, a Java program can load a class that knows the name of a runtime, learns its full construct ( but does not include the methods definition ), and generates its object entity, or set a value on its fields, or evoke its methods. This ability to "see Through" class (the ability of the program to examine itself) is called introspection(introspection, vipassana, introspection). Reflection and introspection are the two terms that are often and are mentioned.

Introduction to the Java Reflection API

In the JDK, the Java reflection mechanism is implemented primarily by the following classes, which are located in the Java.lang.reflect package, except the Class class.

Class: Represents a class that is located under the Java.lang package.

Field class: Represents a member variable of a class (a member variable is also called a property of a class).

Method class: Methods that represent classes.

Constructor class: Represents the construction method of a class.

Array class: Provides a static method for dynamically creating an array, and for accessing the elements of an array.

Class object

To use reflection, you first need to get the class object corresponding to the classes you want to manipulate.

Java   , these objects correspond to the same class object, regardless of how many objects of a class are generated .

This class object is by the JVM generated, through which it is able to learn the structure of the entire class.

  commonly used to get class 3 Ways to object:

1. Use the static method of class. For example: 

Class.forName ("java.lang.String");

2. Use the. class syntax for the classes. Such as:

String.class;

3. Use the GetClass () method of the object. Such as:

String str = "Hello world";

class<?> ClassType = Str.getclass ();

(The GetClass () method is defined in the object class, is not a static method, needs to be called through an object, and it is declared final, indicating that it cannot be overridden by a quilt class. )

Instance:

The routine Dumpmethods class demonstrates the basic role of the reflection API, which reads the class name specified by the command-line arguments, and then prints the method information that the class has. 

Package Com.test.reflection;import Java.lang.reflect.method;public class Dumpmethods{public static void Main (String[] args) throws exception{//loads and initializes the class specified by the command-line arguments (run-time behavior) class<?> ClassType = Class.forName (Args[0]);//Get all the methods of the class method[ ] methods = Classtype.getmethods (); for (int i = 0; i < methods.length; i++) {System.out.println (methods[i]);}}}

The run-time parameters are set to Java.lang.Object output as follows:

Public final native void Java.lang.Object.wait (long) throws Java.lang.InterruptedExceptionpublic final void Java.lang.Object.wait () throws Java.lang.InterruptedExceptionpublic final void java.lang.Object.wait (Long,int) Throws Java.lang.InterruptedExceptionpublic Boolean java.lang.Object.equals (java.lang.Object) public Java.lang.String java.lang.Object.toString () public native int. Java.lang.Object.hashCode () 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 ()

The routine Reflecttester class further demonstrates the basic use of the reflection API. The Reflecttester class has a copy (Object object) method that creates an object of the same type as the Parameter object, and then copies all the properties in the object to the newly created object and returns it.

Package Com.test.reflection;import Java.lang.reflect.field;import Java.lang.reflect.method;public class Reflecttester{public object Copy (Object object) throws exception{//gets the type class ClassType = Object.getclass (); System.out.println ("Class:" + classtype.getname ());//Create a new object by default construction method Object objectcopy = Classtype.getconstructor ( New class[] {}). newinstance (New object[] {});//Get all properties of the Object field fields[] = Classtype.getdeclaredfields (); for (int i = 0; i < Fields.length; i++) {Field field = Fields[i]; String fieldName = Field.getname (); String firstletter = fieldname.substring (0, 1). toUpperCase ();//Get the name of the GetXXX () method that corresponds to the property string getmethodname = "Get" + Firstletter + fieldname.substring (1);//Get the name of the Setxxx () method corresponding to the property string setmethodname = "Set" + Firstletter + Fieldname.substring (1);//Get and attribute corresponding to GetXXX () method GetMethod = Classtype.getmethod (getmethodname,new class[] {});// Get the Setxxx () method corresponding to the attribute Setmethod = Classtype.getmethod (setmethodname,new class[] {field.gettype ()});// Call the GetXXX () method of the original object objECT value = Getmethod.invoke (object, new object[] {}); System.out.println (FieldName + ":" + value);//Call Copy object's Setxxx () method Setmethod.invoke (Objectcopy, new object[] {value});} return objectcopy;} public static void Main (string[] args) throws Exception{customer customer = new Customer ("Tom"); Customer.setid (New Lon G (1)); Customer customercopy = (customer) new Reflecttester (). copy (customer); SYSTEM.OUT.PRINTLN ("Copy information:" + customercopy.getid () + "" + customercopy.getname () + "" + customercopy.getage ()) ;}} Class Customer{private Long id;private string name;private int age;public customer () {}public customer (String name, int age {this.name = Name;this.age = age;} Public Long GetId () {return ID;} public void SetId (Long id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}} /* output:class:com.test.reflection.customerid:1name:tomage:21copy Information:1 Tom 21*/

This example can only copy simple JavaBean, assuming that each property of JavaBean has the getxxx () and Setxxx () methods of the public type.

The Reflecttester class's copy (object) method performs the following steps in turn
(1) The type of the obtained object:
–class Classtype=object.getclass ();
–system.out.println ("Class:" +classtype.getname ());

The GetClass () method is defined in the Java.lang.Object class, so the type of the object can be obtained by this method for any Java object. Class is the core class in the reflection API, and it has the following methods
–getname (): Gets the full name of the class.
–getfields (): Gets the properties of the public type of the class.
–getdeclaredfields (): Gets all the properties of the class.
–getmethods (): Method that gets the public type of the class.
–getdeclaredmethods (): Gets all the methods of the class.

-getmethod (String name, class[] parametertypes): Gets the class's specific method, the name parameter specifies the name of the method, and the Parametertypes parameter specifies the parameter type of the method.
-getconstructors (): Gets the construction method of the public type of the class.
-getconstructor (class[] parametertypes): Gets the specific constructor method for the class, and the Parametertypes parameter specifies the type of the parameter for the constructed method.
-newinstance (): Creates an object of this class from the constructor of the class without parameters.

(2) Create a new object by default construction method:
Object objectcopy=classtype.getconstructor (New class[]{}). newinstance (New object[]{});
The code above calls the class GetConstructor () method to get a constructor object that represents the default construction method, and then calls the constructor object's Newinstance () method to construct an instance.

(3) Get all the properties of the object:
Field Fields[]=classtype.getdeclaredfields ();
The class Getdeclaredfields () method returns all properties of the class, including properties for public, protected, default, and private access levels

(4) Obtain the corresponding getxxx () and Setxxx () methods for each attribute, and then execute these methods to copy the properties of the original object into the new object

About class:

It is well known that Java has an object class, which is the root cause of all Java classes, which declares several methods:hashcode (), Equals (), Clone (), which should be rewritten in all Java classes. ToString (), GetClass (), and so on. where GetClass () returns a class object. Class class is very special. It inherits from the general classes as the object, in fact the body used to express the Java program runtime classes and interfaces, also used to express the enum, array, primitive Java types (Boolean, Byte, char, short, int, long, float, double) and the keyword void. When a class is loaded, or when the defineclass () of the Loader (class loader) is called by the JVM, the JVM automatically generates a Class object. If you want to use "Modify Java standard library source code" to observe the actual generation time of class object (for example, add a println () in the class constructor), not able! Because class does not have public constructor. Class is the origin of reflection. For any class you want to explore, you only have to create a class object for it, and then you can invoke more than 10 reflection APIs through the latter.

How to get the "Class" object

1. Use the GetClass () method to return the class object.

Use Class.getsuperclass () to get the class object of the parent class and return NULL if it is an object class.

2. Using static method Class.forName ()

3. Use the. class syntax. Class name.

The class object of the shaping array can also be obtained in the form of Int[].class.

Wrapper class. The type syntax actually returns a class object of the corresponding native data type.

Calling private methods with reflection, accessing private properties

With reflection, the first is the acquisition of the class object, followed by the method and the Field object.

in the case of method, you can see from the documentation: The GetMethod () method returns the Public method object, the method object returned by Getdeclaredmethod () can be non-public.

field is the same way.

  access to private properties and methods to suppress Java access checks by using the Setaccessible () method in the AccessibleObject class (the base class of the Constructor, field, and method classes) before use .

Instance 1, calling private method: Suppose there is a class that contains a private method.

public class privateclass{    private String SayHello (string name)    {        return "Hello:" + Name;    }}

 Use the reflection mechanism to access the method externally:

Import Java.lang.reflect.method;public class testprivate{public    static void Main (string[] args) throws exception< c1/>{        Privateclass p = new Privateclass ();        class<?> ClassType = P.getclass ();        Get Method Object Method        = Classtype.getdeclaredmethod ("SayHello",                new class[] {string.class});        Method.setaccessible (TRUE); Suppress Java access Control check        //If you do not add the above sentence, you will error:testprivate can not access a member of class Privateclass with modifiers "Priva TE "        String str = (string) Method.invoke (p, new object[] {" Zhangsan "});        System.out.println (str);}    }

Example 2, accessing the private property, directly accessing the private property, and changing the private property in the example to a value.

A class that contains a private property:

public class privateclass2{    private String name = "Zhangsan";    Public String getName ()    {        return name;    }}

Modify the value of its private property with reflection:  

Import Java.lang.reflect.field;public class testprivate2{public    static void Main (string[] args) throws exception< c8/>{        PrivateClass2 p = new PrivateClass2 ();        class<?> ClassType = P.getclass ();        Field field = Classtype.getdeclaredfield ("name");        Field.setaccessible (TRUE); Suppresses Java's checking of modifiers        field.set (p, "Lisi");        System.out.println (P.getname ());}    }

24th Part _java Reflection detailed

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.