Java Reflection Practice __android Learning route

Source: Internet
Author: User
Tags reflection


Reference from: http://www.jianshu.com/p/53eb4e16d00e

Reference from:


what is reflection.

Reflection (Reflection) enables programs that run in the JVM to detect and modify run-time behavior. Class Classes

During a program run, the Java Runtime system always maintains a type identity known as the runtime for all objects. The virtual machine uses run-time information to select the appropriate method to execute. You can access this information through a specialized Java class, and the class that holds the information is called class.

Use Forname and newinstance in the class class to create an object based on the class name stored in the string.

String s = "java.util.Date";
Object m = Class.forName (s). newinstance ();
Why you need reflection.

By reflection, we can detect the types of objects at runtime, dynamically construct objects of a class, detect properties and methods of classes, arbitrarily invoke objects, and modify the visibility of constructors, methods, and properties. JUnit

JUnit traverses the methods that contain @Test annotations through reflection and calls them when they run unit tests. Web Framework

Developers can define implementations of various interfaces and classes in the configuration file. Through the reflection mechanism, the framework can quickly dynamically initialize the required classes.

The spring framework uses the following configuration file:

<bean id= "Someid" class= "Com.programcreek.Foo" > <property name= "Somefield" value=
    "somevalue"/>
</bean>

When the spring container processes the bean element, it initializes the class with Class.forName ("Com.programcreek.Foo") and again uses reflection to get the setter method for the property element to assign a value to the object's properties. Servlet

<servlet>
    <servlet-name>someServlet</servlet-name>
    <servlet-class> Com.programcreek.whyreflectionservlet</servlet-class>
<servlet>
How to use reflection. the basic method of reflection

The principle of not duplicating the wheel, the API detailed reference from here, the following only do a brief introduction.

There are three important classes in the Java.lang.reflect package: field: Describing the domain method of a class: Methods that describe a class constructor: A constructor that describes a class

For public domains (including superclass members): GetFields GetMethods GetConstructors

For other domains (including private and protected members, excluding superclass members): Gettdeclaredfields gettdeclaredmethods gettdeclaredconstructors

The following describes the use of Java reflection, where the person class and the test complete code are at the end of this article. Load Class

    3 Ways to load classes class
    Clazz = Class.forName ("Com.yano.reflect.Person");
    Class clazz1 = new Person (). GetClass ();
    Class class2 = Person.class;
gets the parameterless constructor of the class and instantiates the class
    Class clazz = Class.forName ("Com.yano.reflect.Person");
    Constructor C = clazz.getconstructor (null);
    Person P = (person) c.newinstance (null);
gets the containing parameter private constructor of the class and instantiates the class
    Class clazz = Class.forName ("Com.yano.reflect.Person");
    Constructor C = Clazz
            . Getdeclaredconstructor (New class[] {string.class});
    Because the constructor is private, you need to mask the Java language's access check
    c.setaccessible (true);
    Person P = (person) C
            . newinstance (New object[] {"I ' m a reflect name!"});
gets and invokes the parameterless method of the class
    Class clazz = Class.forName ("Com.yano.reflect.Person");
    Constructor C = clazz.getconstructor (null);
    Person P = (person) c.newinstance (null);
    Method method = Clazz.getmethod ("fun", null);
    Method.invoke (P, NULL);
gets and invokes the parameter-containing method of the class
    Class clazz = Class.forName ("Com.yano.reflect.Person");
    Constructor C = clazz.getconstructor (null);
    Person P = (person) c.newinstance (null);
    Method method = Clazz.getmethod ("Fun", new class[] {string.class});
    Method.invoke (P, new object[] {"I ' m a reflect method!"});
get the fields of a class
    Class clazz = Class.forName ("Com.yano.reflect.Person");
    Constructor C = Clazz
            . Getdeclaredconstructor (New class[] {string.class});
    Because the constructor is private, you need to gain CONTROL permission
    c.setaccessible (true);
    Person P = (person) C
            . newinstance (New object[] {"I ' m a reflect name!"});
    Field f = Clazz.getfield ("name");
    Object value = F.get (p);
    Class type = F.gettype ();
    System.out.println (type);
    if (Type.equals (String.class)) {
        System.out.println ((String) value);
    }
Complete Code

Person class

Package com.yano.reflect;

public class Person {public

    String name = ' default name ';
    Public int[] Array = new INT[10];

    Public person () {
        System.out.println (name);
        for (int i = 0; i < Array.Length i++) {
            array[i] = i;
        }
    }

    Private person (String name) {
        this.name = name;
        SYSTEM.OUT.PRINTLN (name);

    public void Fun () {
        System.out.println ("fun");
    }

    public void Fun (String name) {
        System.out.println (name);
    }

}

Test class

Package com.yano.reflect;
Import Java.lang.reflect.Constructor;
Import Java.lang.reflect.Field;

Import Java.lang.reflect.Method; public class Test {/** * reflection: The byte code of the Load class * * @throws SecurityException * @throws Nosuchmethodexcepti

        On */public static void main (string[] args) throws Exception {Refgetclass ();

        Gets and invokes the parameterless constructor Refgetpublicconstructor ();

        Gets and invokes the private containing parameter constructor Refgetprivateconstructor ();

        Gets and invokes the parameterless method fun Refgetmethodwithnoarg ();

        Gets and invokes a parametric method fun refgetmethodwitharg ();
    Gets the field of the class Refgetfield (); private static void Refgetfield () throws Exception {Class clazz = Class.forName ("Com.yano.reflect.Person"
        );
        Constructor C = clazz. Getdeclaredconstructor (New class[] {string.class});
        Because the constructor is private, you need to gain CONTROL permission c.setaccessible (true); Person P = (person) c. newinstance (New ObjecT[] {"I ' m a reflect name!"});
        Field f = Clazz.getfield ("name");
        Object value = F.get (p);
        Class type = F.gettype ();

        System.out.println (type);
        if (Type.equals (String.class)) {System.out.println ((String) value);
    } System.out.println (); private static void Refgetmethodwitharg () throws Exception {Class clazz = Class.forName ("Com.yano.reflect .
        Person ");
        Constructor C = clazz.getconstructor (null);

        Person P = (person) c.newinstance (null);
        Method method = Clazz.getmethod ("Fun", new class[] {string.class});
        Method.invoke (P, new object[] {"I ' m a reflect method!"});
    System.out.println (); private static void Refgetmethodwithnoarg () throws Exception {Class clazz = Class.forName ("Com.yano.refle Ct.
        Person ");
        Constructor C = clazz.getconstructor (null);

        Person P = (person) c.newinstance (null); Method method = Clazz.getmethoD ("fun", null);
        Method.invoke (P, NULL);
    System.out.println (); private static void Refgetprivateconstructor () throws Exception {Class clazz = Class.forName ("Com.yano.re Flect.
        Person ");

        Constructor C = clazz. Getdeclaredconstructor (New class[] {string.class});

        Because the constructor is private, you need to mask the Java language's access check c.setaccessible (true);
        Person P = (person) c. newinstance (new object[] {"I ' m a reflect name!"});
    System.out.println (); private static void Refgetpublicconstructor () throws Exception {Class clazz = Class.forName ("Com.yano.ref Lect.
        Person ");

        Constructor C = clazz.getconstructor (null);
        Person P = (person) c.newinstance (null);
    System.out.println (); 3 methods of the private static void Refgetclass () throws ClassNotFoundException {//load class Clazz = CLASS.F
        ORName ("Com.yano.reflect.Person"); Class clazz1 = new Person (). GetClass ();
        Class class2 = Person.class;
    System.out.println (); }

}


The man who is called L (Jane book author)
Original link: http://www.jianshu.com/p/53eb4e16d00e
Copyright belongs to the author, reproduced please contact the author to obtain authorization, and labeled "Jane book author."

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.