Reflection in the Kotlin/java notes

Source: Internet
Author: User
Tags reflection
What is Reflection

Reflection is a computer processing method. A program has the ability to access, detect, and modify its own state or behavior. can provide an object that encapsulates an assembly, type.
For the OOP language of Java, in the running state, we can restore "all the information of class" according to "partial information of Class", this is the reflection in Java. Architecture of Java virtual machines

The Java Virtual machine masks information related to the specific operating system platform, allowing Java programs to generate only the target code (bytecode) that runs on the Java Virtual machine, and can be run unmodified on a variety of platforms. In layman's parlance, Java virtual machines are virtual machines that deal with Java programs (literally Java bytecode).
As a virtual machine, the structure of the JVM is consistent with the common operating system, with its own heap, stack, method area, PC counter, and instruction system. Its structure is shown in the following illustration:
Here we are not going to talk about class loading subsystem and execution engine, just talking about the data area of the Java runtime, which consists of five parts:
Image.png

(1) Program counter (thread private)
The program counter is the line number indicator of the byte code executed by the current thread, and the bytecode interpreter works by changing the value of this counter to select the next byte code instruction to execute.
Basic functions such as branching, looping, jumping, exception handling, and thread recovery need to be relied upon for this counter to complete.
At any given moment, a processor (which is a kernel for multi-core processors) executes only the instructions in a single thread.
Therefore, in order to return to the correct execution position after the thread switch, each thread needs to have a separate thread counter, the counters between the threads do not affect each other, isolated storage.
(2) Virtual machine stack (thread private)
In the Java (or other JVM language), each method is executed with a stack frame that stores information such as local variable tables, operand stacks, dynamic links, method exits, and so on.
Each method is invoked until the completion of the process, corresponding to a stack frame in the virtual machine stack from the stack to the process.
The Java Virtual machine stack holds local variable tables, such as the various basic data types known at compile time (Boolean, Byte, char, short, int, float, long, double), object reference (reference type, which is not equivalent to the object itself). Depending on the virtual machine implementation, it may be a reference pointer to the starting address of the object, or it may point to a handle to the object or to the location associated with the object, and the ReturnAddress type, which points to the address of a byte-code directive.
This also causes the free variables within the anonymous inner class from the external closure environment in Java to be final (the Java compiler is Capture-by-value mode), but there is no such limit in Kotlin. It implements Capture-by-reference by automatic wrapping (so it has no basic type).
(3) Local method stack (thread private)
Similar to the virtual machine stack, the difference is that the virtual machine stack performs Java methods (that is, bytecode) services, while the local method stack is the native method used for the virtual machine.
(4) heap (thread sharing)
is the largest piece of memory managed by a Java virtual machine. The Java heap is an area of memory that is shared by all threads and is created when the virtual machine is started. The only purpose of this memory area is to hold the object instance, where almost all object instances allocate memory.
The Java heap is the main area of garbage collector management, and is often referred to as a "GC heap" (Garbage collected Heap). Since now the collector is basically the use of the collection algorithm, so the Java heap can also be subdivided into: the new generation and the old age.
(5) Method area (thread sharing)
The method area is used to store data such as class information, constants, static variables, and Just-in-time compiler-compiled code that have been loaded by the virtual machine.
Specifically, for each class we use in Java programs, it generates a corresponding class file in the method area, which records the following information:
(If you want to know more information, you can refer to http://blog.csdn.net/luanlouis/article/details/39892027), here is a brief explanation.
1. Class Information
2. Field information
3. Method information
4. Constant pool
5. Class variable (statically static field, or companion object)
Reference to 6.classLoader
References to 7.class objects
8. Method table
Because this information is recorded in real time in the method area of the JVM, we can get all the information about the class at run time, and the key is to get its corresponding class object.Get Class object

In Java, there are several ways to get a class object:
1:class.forname ("Class name string") (Note: Class name string must be full name, package name + class name)
2: Class name. class
3: Instance object. GetClass ()

    public void Getclasstest ()
    {
       try{
           Class baseinfo = Class.forName ("Com.suiseiseki.www.BaseInfo");
           Class object = Object.class;
           Class date = (new Date ()). GetClass ();
           Class TestClass = This.getclass ();
       }
       catch (Exception e)
       {
           e.printstacktrace ();
       }
    }
Restore information for a class gets the constructor for the class

Java provides the following APIs for getting the construction method of a class:

Gets the public constructor for "parameter is parametertypes" public
constructor    GetConstructor (class[] parametertypes)
// Gets the entire public constructor public
constructor[]    getconstructors ()
//get "argument is Parametertypes" and is a constructor declared by the class itself. Contains public, protected, and private methods. Public
Constructor    Getdeclaredconstructor (class[] parametertypes)
//Get all constructors declared by the class itself, including public, Protected and private methods. Public
constructor[]    getdeclaredconstructors ()
//If this class is an inner class in the constructor of another class, call Getenclosingconstructor () is the constructor in which this class is located, and returns NULL if it does not exist. Public
Constructor    Getenclosingconstructor ()

For example:

public class Test1 {public void TestConstructor () {try{Class C = Country.class;
           Gets public the parameterless constructor constructor origin = C.getdeclaredconstructor (); Gets the constructor for private (note that Int.class is not integer.class) constructor cst2 = C.getdeclaredconstructor (New class[]{int.class,i
           Nt.class});

           The constructor is private, so this is set to accessible cst2.setaccessible (true);
           Country C1 = (Country) origin.newinstance ();
           Country C2 = (Country) cst2.newinstance (30,100);
           SYSTEM.OUT.PRINTLN (C1);
       System.out.println (C2);
    ' Catch (Exception e) {}} ' class country{public int pop;
    public int money;
        Public Country () {pop = 0;
    Money = 0;
        Private Country (int pop,int money) {this.pop = Pop;
    This.money = money;
    @Override public String toString () {return "pop" +pop+ "money:" +money; } public void Doublepop() {This.pop = This.pop * 2;
        private int Multimoney (int n) {This.money = This.money*n;
    return This.money;
 }

}

After you get to the constructor, you can call the constructor's newinstance to create the object. As you can see in the example, reflection can access the private domain of the class, and you can modify it to use a hidden constructor. gets the method of the class

In Java, the method is wrapped as a method object, and the API for getting the methods object of the class is as follows:

Gets the public function named name, parameter is Parametertypes, which includes all public functions implemented from the interface from the base class    GetMethod (String name , class[] parametertypes
//Get all public functions (including all public functions inherited from the base class, implemented from the interface) public
method[]    getmethods ()
//Get "name is named, parameter is Parametertypes", and is a function declared by the class itself, containing public, protected, and private methods. Public    Method Getdeclaredmethod (String name, class[] parametertypes)
//Gets all the functions declared by the class itself, including public, Protected and private methods. Public
method[]    getdeclaredmethods ()
//If this class is the inner class of a method in another class, calling Getenclosingmethod () is the method in which this class resides If it does not exist, return null. Public method    Getenclosingmethod ()

For example, the following method gets the method and calls:

    public void TestMethod ()
    {
        try{
            Class c = country.class;
            Country country3 = new Country ();
            Country3.money = m;
            Country3.pop = 3;
            Get public methods (no arguments, no return values) method
            Mdoublepop = C.getmethod ("Doublepop", New class[]{});
            Invoke the Invoke execution method, which requires passing in an object of the class
            Mdoublepop.invoke (Country3);
            System.out.println (country3);
            Gets the public method (with parameters, there are return values) methods
            Mmultimoney = C.getmethod ("Multimoney", New Class[]{int.class});
            Mmultimoney.setaccessible (true);
            Mmultimoney.invoke (country3,42);
            System.out.println (Country3);
        }
        catch (Exception e) {}
    }

Corresponding method:

    public void Doublepop ()
    {
        This.pop = This.pop * 2;
    }

    private int Multimoney (int n)
    {
        This.money = this.money*n;
        return This.money;
    }
get the member variable of a class

In Java, a member variable is called a Field object, and the API to get the class member variable is as follows:

Gets the member variable of public, named Name, which includes all public member variables that are implemented from the interface, which is inherited from the base class, public
Field    GetField (String name)
/ Gets all public member variables, including all public member variables implemented from the interface from the base class, public
field[]    getfields ()
//Gets "name is named" and is a member variable declared by the class itself that contains public, protected, and private member variables. The public
Field    Getdeclaredfield (String name)
//Gets the member variables declared by the entire class itself, including public, protected, and private member variables. Public
field[]    getdeclaredfields ()

For example:

    public void Fieldtest ()
    {
        try{
            Class c = country.class;
            Country Country4 = new Country ();
            Country4.money = m;
            Country4.pop = 3;

            Field Fpop = C.getfield ("Pop");
            Fpop.set (42,COUNTRY4);
            System.out.println (COUNTRY4);
        }
        catch (Exception e) {}
    }

Note the issue of permissions, if you do not have permissions, you need to setaccessible (true), or else you will throw additional information about the exception class 1. Annotations

Gets the annotations of the class's "Annotationclass" type, including all public member variables implemented from the interface, that are inherited from the base class, public
annotation<a>    getannotation ( Class Annotationclass)
//Get all the annotations of the classes (including all public member variables that are implemented from the interface, inherited from the base class) public
annotation[]    getannotations ()
//Get all the annotations declared by the class itself (including public, protected, and private member variables) public
annotation[]    getdeclaredannotations ()

Now we can write programs that automatically process annotations in a program, such as depending on the annotation to decide whether to process a class:

    public void Handlemyannotation (list<class> List)
    {for
        (Class clazz:list)
        {
            if ( Clazz.getannotation (Myannotation.class))
            {
                println ("This class is under Annotation");
            }
        }
    

Many well-known open source libraries (DAGGER2,GSON,RETROFIT,ASPECTJ), etc. are done through reflection + annotations, which facilitate the writing of programs while also bringing some performance overhead (although they have done their best to optimize),
Reflection in the load period to do things to move to the runtime, so the compiler can not be related to the code optimization. 2. Interface and base class

Get all interfaces for implementation public
type[]    getgenericinterfaces ()
//Get base class public
type    Getgenericsuperclass ()

Note that the base class for reflection fetching is a direct base class (that is, to get only the previous level), and to get the inheritance chain, further traversal of the 3

is required.

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.