High-level reflection of Java

Source: Internet
Author: User
Tags readline

——-Android Training, Java training, look forward to communicating with you! ———-

Java Advanced Reflection One 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
Two-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
Three-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.
    • B: Three different ways

      • The GetClass () method of the A:object class determines whether two objects are the same bytecode file, such as New Date (). GetClass ();
      • B: Static attribute class, lock object
      • C:class class static Method Forname (), read the configuration file, such as Class.forName ("java.util.Date");
    • C: Case Demo
      • Three ways to get a class file object
 Public classreflecttest{ Public Static voidMain (string[] args) throws Exception {String str ="ABC";        Class cls1 = Str.getclass (); Class cls2 = String.class; Class CLS3 = Class.forName ("Java.lang.String");//Description They are the same byte codeSystem. out. println (CLS1==CLS2);//trueSystem. out. println (CLS1==CLS3);//trueSystem. out. println (Cls1.isprimitive ());//falseSystem. out. println (int.class. isprimitive ());//trueSystem. out. println (int.class= = Integer.class);//falseSystem. out. println (Integer.class. isprimitive ());//falseSystem. out. println (int.class= = Integer.type);//trueSystem. out. println (int[].class. isprimitive ());//falseSystem. out. println (int[].class. IsArray ());//true

Operation Result:

Note:
Class instance object of array type
Class.isarray ();

    • In short, as long as the types that appear in the source program have their own class sample objects such as int[] void ...
Four-Reflection (Class.forName () read configuration file example)
    • Juice Extractor (Juicer) Case of juicing
    • Fruit (Fruit) apple (apple) banana (Banana) orange (orange) Juice (squeeze)
/* Juice extractor (juicer) juice routinely respectively fruit (Fruit) Apple banana orange Juice Note: This example in order to highlight the core code, no exception handling * *Import java.io.*; Public  class reflectdemo{     Public Static voidMain (string[] args) throws Exception {//No reflection only polymorphic//Juicer J = new Juicer ();//Buy Juice Extractor//J.run (new Apple); //Throw an apple into the juicer//J.run (New Orange ());        //Using reflection and configuration files        //Create stream object, associate configuration fileBufferedReader br =NewBufferedReader (NewFileReader ("D:\\config.properties"));//, gets the byte code object of the class, reads the configuration file one line of contentClass clazz = Class.forName (Br.readline ());//Create an object instance from a bytecode objectFruit f = (Fruit) clazz.newinstance ();//Parent reference to child class object The reference to the fruit is pointing to the Apple objectJuicer J =NewJuicer ();//Create a Juicer objectJ.run (f); }} interface Fruit{     Public voidSqueeze ();} class Apple implements Fruit{     Public voidSqueeze () {System.out.println ("Squeeze apple Juice"); }} class Orange implements Fruit{     Public voidSqueeze () {System.out.println ("Squeeze the orange juice."); }} class juicer{     Public voidRun (Fruit f) {f.squeeze (); }}

Operation Result:

Summary:
By reflection, the application of the code is greatly simplified. In this example, to change the function of the program only need to modify the corresponding configuration file, rather than a lot of trouble to modify the source.
On the other hand, the security and robustness of the program are greatly enhanced.

Five-reflection (get 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
        Example code:
/* Note: for easy programming. This example does not add the person class. * / import java.lang.reflect.*; class ReflectDemo2{     Public Static voidMain (string[] args) throws Exception {Class clazz = Class.forName ("Person");//person P = (person) clazz.newinstance ();//Construct an object by using no parameter//System.out.println (p);        //Get parametric constructsConstructor C = Clazz.getconstructor (String.classInt.class);//Create an object through a parameter constructPerson P = (person) c.newinstance ("Zhang San", A);    SYSTEM.OUT.PRINTLN (P); }}

Operation Result:

Six reflections (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.

The code is implemented as follows:

 import java.lang.reflect.*; class ReflectDemo3{     Public Static voidMain (string[] args) throws Exception {Class clazz = Class.forName ("Person"); Constructor C = Clazz.getconstructor (String.classInt.class); Person P = (person) c.newinstance ("Zhang San", A);//Because the last Name field is private and therefore cannot be obtained        //field f = Clazz.getfield ("name");//Get Last Name field        //f.set (P, "John Doe");//Modify name        //Get field by violent reflectionField f = Clazz.getdeclaredfield ("Name"); F.setaccessible (true);//Remove PermissionsF.Set(P,"John Doe");    SYSTEM.OUT.PRINTLN (P); }}

Operation Result:

Seven Reflections (Get the 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)

Example code:

 import java.lang.reflect.*; class ReflectDemo4{     Public Static voidMain (string[] args) throws Exception {Class clazz = Class.forName ("Person"); Constructor C = Clazz.getconstructor (String.classInt.class); Person P = (person) c.newinstance ("Zhang San", A); Method m = Clazz.getmethod ("Eat");//Get method methodsM.invoke (P); Method m2 = Clazz.getmethod ("Eat"Int.class);//Get a method with a parameterM2.invoke (P,Ten);//Operating release method}}

Operation Result:

Eight reflections (through reflection over the generic check)
    • A: Case Demo
      • ArrayList an object that adds a string of data to this collection, how does it work?
/* * A: Case demo generic erase generic Reflection * arraylist<integer> An object that adds a string of data to this collection, how do you do it? Generics are only valid at compile time and will be erased during run time * / import java.util.*; import java.lang.reflect.*; class ReflectTest1{     Public Static voidMain (string[] args) throws Exception {arraylist<integer> list =NewArraylist<integer> (); List.add (111); List.add (222);//Get byte-code objectClass clazz = Class.forName ("Java.util.ArrayList");//Get the Add methodMethod m = Clazz.getmethod ("Add", Object.class); M.invoke (list,"ABC");//Operating methodSYSTEM.OUT.PRINTLN (list); }}

Operation Result:

Summary:
Generics are only valid at compile time and will be erased during run time

Nine Reflections (write 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.
Import Java.lang.reflect.*;class reflecttest2{ Public Static void Main(string[] args) throws Exception {//Create student instancesStudent s =NewStudent ("Zhang San", at); System. out. println ("Pre-modification information:"+s); Tool T =NewTool ();//Create a tool class instanceT.setproperty (s),"Name","John Doe"); System. out. println ("modified message:"+s); }}//Tool classClass tool{//This method sets the value of the property named PropertyName in the Obj object to     Public void SetProperty(Object obj, String PropertyName, Objectvalue) throws Exception {Class clazz = Obj.getclass ();//Get byte-code objectField f = Clazz.getdeclaredfield (PropertyName);//Violent reflex get fieldF.setaccessible (true);//Remove PermissionsF.Set(obj,value); }} class student{PrivateString name;Private intAge Public Student()//non-parametric construction method {} Public Student(String name,intAge)//The method of constructing a parameter { This. name = name; This. Age = Age; } PublicStringGetName()    {returnName } Public int Getage()    {returnAge } Public void SetName(String name) { This. name = name; } Public void Setage(intAge) { This. Age = Age; } PublicStringtoString()    {return "Name="+name+", "+"Age="+age; }}

Operation Result:

Ten Reflections (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.
 import java.io.*; import java.lang.reflect.*; class ReflectTest3{     Public Static voidMain (string[] args) throws Exception {//Create an Input stream association configuration fileBufferedReader br =NewBufferedReader (NewFileReader ("D:\\xxx.txt")); Class clazz = Class.forName (Br.readline ());//Read the class name in the configuration file to get the bytecode objectDemoClass DC = (DemoClass) clazz.newinstance ();//Create an object from a byte-code objectDc.run (); }} class DemoClass{     Public voidRun () {System.out.println ("Welcome to Heima"); }}

Operation Result:

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)

——-Android Training, Java training, look forward to communicating with you! ———-

High-level reflection of Java

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.