Java-reflect (Reflection) Preliminary understanding _1

Source: Internet
Author: User

27.01_ Reflection (class loading overview and loading time)

    • A: Overview of loading classes
      • When a program wants to use a class, if the class has not yet been loaded into memory, the system initializes the class by loading, connecting, and initializing three steps.
      • Load
        • This means reading the class file into memory and creating a class object for it. When any class is used, the system creates a class object.
      • Connection
        • Verify that you have the correct internal structure and that it is consistent with other classes
        • Prepare to allocate memory for static members of the class and set default initialization values
        • Resolve to replace a symbolic reference in a class's binary data with a direct reference
      • Initialization is the initial step we've talked about before.
    • B: Loading time
      • To create an instance of a class
      • Access static variables for a class, or assign a value to a static variable
      • To invoke a static method of a class
      • Use reflection to force the creation of a Java.lang.Class object for a class or interface
      • Initializes a subclass of a class
      • To run a main class directly using the Java.exe command

27.02_ Reflection (Overview and classification of Class loaders)

    • A: Overview of Class Loaders
      • Responsible for loading the. class file into memory and generating the corresponding class object for it. Although we do not need to care about the class loading mechanism, we understand this mechanism and we can better understand the operation of the program.
    • B: Class Loader classification
      • Bootstrap ClassLoader Root class Loader
      • Extension ClassLoader Extension Class loader
      • Sysetm ClassLoader System Class Loader
    • C: The role of the class loader
      • Bootstrap ClassLoader Root class Loader
        • Also known as the Boot class loader, which is responsible for loading Java core classes
        • such as system,string and so on. In the Rt.jar file under the Lib directory of the JRE in the JDK
      • Extension ClassLoader Extension Class loader
        • Responsible for loading the jar packages in the extended directory of the JRE.
        • The Lib directory of the JRE in the JDK under the EXT directory
      • Sysetm ClassLoader System Class Loader
        • Responsible for loading the class file from the Java command when the JVM starts, and the jar package and classpath specified by the CLASSPATH environment variable

27.03_ Reflection (Reflection Overview)

    • A: Reflection Overview
      • Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class;
      • For any object, it 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.
      • To dissect a class, you must first obtain the bytecode file object for that class.
      • The anatomy uses the method in class, so we first get the object of class type for each bytecode file.
        Source file Stage bytecode stage create object stage
        Person.java person.class Person p = new person ()
        Three stages corresponding to-------------------------------------------------------------------------------------------reflection
        Class Clazz = Class.forName ("Class name") Class Clazz = Person.class Class clazz = P.getclass ()
        Read the configuration file as a static method of the lock object to determine whether it is the same byte-code file
    • B: Three different ways
      • The GetClass () method of the A:object class to determine whether two objects are the same byte-code file
      • B: Static attribute class, lock object
      • static method Forname () in the C:class class, reading the configuration file
    • C: Case Demo
      • Three ways to get a class file object

27.04_ Reflection (Class.forName () read configuration file example)

  • Juice Extractor (Juicer) Case of juicing
  • Fruit (Fruit) apple (apple) banana (Banana) orange (orange) Juice (squeeze)
    public class Demo2_reflect {
    /**
    * Juicer (Juicer) Juice Case
    * fruit (Fruit) apple (apple) banana (Banana) orange (orange) Juice (squeeze)
    * @throws Exception
    /
    public static void Main (string[] args) throws Exception {
    /
    Juicer j = new Juicer ();
    J.run (New Apple ());
    J.run (New Orange ()); */
    BufferedReader br = new BufferedReader (New FileReader ("Config.properties"));//create an input stream object, The associated configuration file. Use BufferedReader to read one line of
    class<?> clazz = Class.forName (Br.readline ());//Read the configuration file line, get the bytecode object of the class
    Fruit f = (Fruit) clazz.newinstance (); Creates an instance object from a bytecode object, Clazz.newinstance () returns an object of type objects, so a type conversion is required (Fruit)
    Juicer j = new Juicer ();
    J.run (f);

      }}interface Fruit {  public void squeeze();}class Apple implements Fruit {  public void squeeze() {      System.out.println("榨出一杯苹果汁儿");  }}class Orange implements Fruit {  public void squeeze() {      System.out.println("榨出一杯桔子汁儿");  }}class Juicer {  public void run(Fruit f) {      f.squeeze();  }}

27.05_ Reflection (acquisition of the parameter construction method by reflection and use)

    • Constructor
      • The Newinstance () method of class is to create an object using the parameterless constructor, and if a class does not have a parameterless constructor, it cannot be created and can call the class GetConstructor (String.class, Int.class) method to get a specified constructor and then call the Newinstance ("Zhang San", 20) method of the constructor class to create the object

27.06_ reflection (Get member variables by reflection and use)

    • Field
      • The Class.getfield (String) method can get the specified field in the class (visible) and, if it is private, can be obtained by using the Getdeclaedfield ("name") method, which sets the value of the field on the specified object through the set (obj, "John Doe") method. If it is private, you need to call Setaccessible (true) to set the access permission, and call Get (obj) with the specified field to get the value of the field in the specified object.

27.07_ reflection (Get method by reflection and use)

    • Method
      • Class.getmethod (String, class ...) and Class.getdeclaredmethod (String, class ...) The method can get the specified method in the class, invoke invoke (object, Object ...). You can call this method, Class.getmethod ("Eat") Invoke (obj) Class.getmethod ("Eat", Int.class) Invoke (obj,10)

27.08_ Reflection (cross-check through reflection)

    • A: Case Demo
      • ArrayList

27.09_ Reflection (writes a common setting by reflection a property of an object to a specified value)

    • A: Case Demo
      • public void SetProperty (Object obj, String PropertyName, Object value) {}, which sets the value of the property named PropertyName in the Obj object to values.

27.10_ Reflex (practice)

    • A class is known to be defined as follows:
      • Package Cn.itcast.heima;
        • public class DemoClass {
          public void Run () {
          System.out.println ("Welcome to heima!");
          }
          }
      • (1) Write a configuration file in the properties format, and configure the full name of the class.
      • (2) Write a program, read the properties configuration file, get the full name of the class and load the class, and run the Run method in a reflective manner.

27.11_ Reflection (Overview and implementation of dynamic proxies)

    • A: Dynamic Agent Overview
      • Agent: Should have done their own things, please others to do, the person invited is the agent object.
      • Example: The Spring Festival home to buy tickets for people
      • Dynamic Agent: This object is produced during the process of running the program, and the object that is generated during the program operation is actually the content that we just reflected, so the dynamic agent is actually generating an agent through reflection.
      • In Java, a proxy class and a Invocationhandler interface are provided under the Java.lang.reflect package, and dynamic proxy objects can be generated by using this class and interface. The proxy provided by the JDK can only be proxied for the interface. We have more powerful proxies in the Cglib,proxy class to create a dynamic proxy class object
      • public static Object newproxyinstance (ClassLoader loader,class<?>[] Interfaces,invocationhandler h)
      • The method that will eventually call Invocationhandler
      • Invocationhandler object Invoke (Object Proxy,method method,object[] args)

Java-reflect (Reflection) Preliminary understanding _1

Related Article

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.