Class loading, timing, reflection, template design, jdk7/jdk8 new features (26)

Source: Internet
Author: User

1. Loading overview and loading time for classes

* A: Loading overview for classes
* When the program wants to use a class, if the class has not yet been loaded into memory, the system will initialize the class by loading, connecting, and initializing three steps.
* Load
* Means to read the class file into memory and create a class object for it. When any class is used, the system creates a class object.
* Connection
* Verify the correct internal structure and coordinate with other classes
* Prepare to allocate memory for static members of the class and set default initialization values
* Parsing replaces symbolic references in binary data of a class with direct references

* Initialization is the initial step we've talked about before
* B: Loading time
* Create an instance of a class
* Access static variables for a class, or assign a value to a static variable
* Static method of calling class
* Use reflection to force the creation of a class or interface corresponding to the Java.lang.Class object
* Initialize subclasses of a class
* Use the Java.exe command directly to run a main class.

2. 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: Role of 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.
* In the JDK of the JRE in the Lib directory of 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.

3. Overview of Reflections

* Overview of the Class<t> class:
* Instances of the 1.Class class represent classes and interfaces in a running Java application.
* 2.Class There is no public construction method.
* 3.Class objects are constructed automatically by the Java virtual machine and by invoking the DefineClass method in the class loader when the class is loaded.

* A: Reflection Overview
* 1.JAVA reflection mechanism is in the running state, for any class, can know all the properties and methods of the class;
* 2. For any object, it can call any of its methods and properties;
* 3. This dynamically acquired information and the ability to dynamically invoke the object's methods are called the Java language's reflection mechanism.
* 4. To dissect a class, you must first obtain the bytecode file object for that class.
* 5. 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 1:object class to determine whether two objects are the same byte-code file
* Person P = new person (); Create an Object
* Class clazz2 = P.getclass (); Call the GetClass () method in this object (which inherits from the class object), the return type is class
* 2: Static attribute class, lock object
* Class clazz = Person.class; Class name. Call, return type is class
* Static method Forname () in 3:class class, read configuration file
* Class clazz = class.forname ("xxx.properties");
* Configuration file creation, suffix name is. Properties, creates a profile throughout the project.

4.class.forname () Read configuration file example

* Class.forName (String className) return type is class, parameter is the string name of the class or interface
* Juicer (Juicer) Juice case
* Fruit (Fruit) apple (apple) banana (Banana) orange (orange) Juice (squeeze)

 Public classDemo2_reflect {/*** Juicer (Juicer) Juice case * fruit (Fruit) apple (apple) banana (Banana) orange (orange) Juice (squeeze) *@throwsException*/             Public Static voidMain (string[] args)throwsException {/*Juicer j = new Juicer ();                J.run (New Apple ()); J.run (New Orange ());*/bufferedreader BR=NewBufferedReader (NewFileReader ("config.properties"));//Create an input stream object, associate a configuration fileClass<?> clazz = Class.forName (Br.readline ());//reads a single line of the configuration file to get the bytecode object for that classFruit f = (Fruit) clazz.newinstance ();//creating an instance object from a byte-code objectJuicer J =NewJuicer ();            J.run (f); }                }        InterfaceFruit {//define an interface             Public voidsqueeze (); }                classAppleImplementsFruit {//define an Apple class inheritance interface             Public voidsqueeze () {System.out.println ("Squeeze out a cup of apple juice."); }        }                classOrangeImplementsFruit {//define an Orange class inheritance interface             Public voidsqueeze () {System.out.println ("Squeeze out a glass of orange juice."); }        }                classJuicer {//Define a Juicer class             Public voidrun (Fruit f) {f.squeeze (); }                }

5. Obtain the parameter construction method by reflection and use the

* Constructor
* 1.Constructor provides information about a single construction method of a class and access to it.
* 2.Constructor allows extended conversions when newinstance () matches a formal parameter with the underlying constructor method, but throws illegalargumentexception if a narrowing conversion occurs.
* Class
* The Newinstance () method of the 1.Class class is to create an object using the class's parameterless constructor, which cannot be created if a class has no parameterless constructors.
* 2. However, you can call the class GetConstructor (String.class,int.class) method to get a specified constructor.
* 3. Then call the Newinstance ("Zhang San", 20) method of the constructor class to create the object.

6. Get member variables by reflection and use

* Field
The Class.getfield (String) method can get the specified field (visible) in the class, and if it is private, it 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.

7. 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).

* A class is known, defined as follows      :package  Cn.itcast.heima     ; * Public         class  DemoClass {                publicvoid  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.

8. Overview and implementation of dynamic agents

* A: Dynamic Agent Overview
* Agent: Should have done their own things, please others to do, the person invited is the agent object.
* Example: Spring home to buy tickets for the purchase of people
* Dynamic Agent: The object generated during the process of running the program, and the process of running the object is actually what we just reflected the content of the explanation, so, dynamic agent is actually through reflection to generate a proxy

* A proxy class and a Invocationhandler interface are provided under the Java.lang.reflect package in Java to generate dynamic proxy objects 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)
* method that will eventually call Invocationhandler
* Invocationhandler Object Invoke (Object Proxy,method method,object[] args)

9. Template design mode overview and use

* A: Template design mode overview
* Template method mode is defined as the skeleton of an algorithm, and the specific algorithm is deferred to the subclass to achieve
* B: Pros and cons
* A: Advantages
* Using the template method mode, in defining the algorithm skeleton, can be very flexible to achieve the specific algorithm to meet the user's flexible needs
* B: Cons
* If the algorithm skeleton is modified, you need to modify the abstract class
1, Decoration
2, single case
3, Simple Factory
4, Factory method
5, adapter
6, Stencil

Six new features of 10.JDK7

* A: Binary literals
* B: Digital literals can appear underlined
* The C:switch statement can be used as a string
* D: Generics simplified, diamond generic
* E: Exception of multiple catch merges, per exception with or |
* F:try-with-resources Statement

New features of 11.JDK8

* Methods in the interface can be defined with the method body, if non-static, must be modified with the default
* If it's static, it's not.

Class loading, timing, reflection, template design, jdk7/jdk8 new features (26)

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.