Java EE Fundamentals (27)/reflection, JDK new features

Source: Internet
Author: User

1, 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
2, Reflection (class loader overview and classification)
    • 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
3. 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 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
4, Reflection (Class.forName () read the 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, associate the configuration file class<?> clazz = Class.forName (Br.readline ());                                          Reads a line of contents of the configuration file, gets the bytecode object of the class Fruit F = (Fruit) clazz.newinstance ();        Creating an instance object from a bytecode object juicer j = new Juicer ();    J.run (f); }}interface Fruit {public void Squeeze ();}    Class Apple implements Fruit {public void squeeze () {System.out.println ("squeeze out a cup of apple juice");    }}class Orange implements Fruit {public void squeeze () {System.out.println ("squeeze out a glass of orange juice");    }}class Juicer {public void run (Fruit f) {f.squeeze (); }} 
5, reflection (through reflection to obtain the structural method of the parameter 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
6. 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.
7, reflection (through reflection to obtain the method 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)
8, reflection (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?
9. Reflection (Write a common setting by reflection a property of an object is 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.
10. Reflection (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.
11, Reflection (Dynamic Agent overview and implementation)
    • 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)
12, design mode (template) design mode overview and use
    • A: Overview of template Design Patterns
      • The template method pattern is defined as the skeleton of an algorithm, and the specific algorithm is deferred to the subclass to realize
    • B: Pros and cons
      • A: Advantages
        • Using the template method mode, in defining the skeleton of the algorithm, we can implement the concrete algorithm flexibly, and satisfy the user's flexible and changeable demands.
      • B: Cons
        • If the algorithm skeleton is modified, you need to modify the abstract class 1, decorate 2, Singleton 3, simple factory 4, factory method 5, adapter 6, template
13, JDK5 new features (self-Implementation enumeration Class)
    • A: Enumeration Overview
      • is to list the value of the variable one by one, and the value of the variable is limited to the range of values enumerated. Example: only 7 days a week, only 12 months a year.
    • B: Recall the singleton design pattern: A singleton class is a class with only one instance
      • So many examples are a class with multiple instances, but not an infinite number of instances, but a finite number of instances. This can be an enumeration class.
    • C: Case Demo
      • Self-implemented enumeration Class 1, Automatic Disassembly box 2, generics 3, variable parameter 4, static import 5, enhanced for loop 6, mutex 7, enumeration
14. JDK5 new Feature (enum class via Enum)
    • A: Case Demo
      • Implementing enum classes with enum
15. JDK5 new features (enumeration considerations)
    • A: Case Demo
      • Defining enum classes to use the keyword enum
      • All enum classes are subclasses of enum
      • The first line of an enumeration class must be an enumeration item, and the semicolon after the last enumeration item can be omitted, but the semicolon cannot be omitted if there is something else in the enumeration class. It is recommended not to omit
      • An enumeration class can have a constructor, but it must be private, and it defaults to private.
      • An enumeration class can also have an abstract method, but an enumeration item must override the method
      • Use of enumerations in a switch statement
16. JDK5 new Features (common methods for enumerating classes)
    • A: Common ways to enumerate classes
      • int ordinal ()
      • int CompareTo (E o)
      • String name ()
      • String toString ()
      • T valueOf (Class type,string name)
      • VALUES ()
      • Although this method is not found in the JDK document, each enumeration class has that method, and it is convenient to traverse all enumerated values of the enumeration class
    • B: Case Demo
      • Common ways to enumerate classes
17, JDK7 new features (six new features of JDK7 Review and explanation)
    • A: Binary literals
    • B: The digital literal can appear underlined
    • The C:switch statement can use a string
    • D: Generic simplification, diamond generics
    • E: Multiple catch merges for exceptions, each with or |
    • F:try-with-resources statements
18. New features of JDK8 (new features of JDK8)
    • The method 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 Test {    public void run() {        final int x = 10;        class Inner {            public void method() {                System.out.println(x);            }        }        Inner i = new Inner();        i.method();    }}局部内部类在访问他所在方法中的局部变量必须用final修饰,为什么?因为当调用这个方法时,局部变量如果没有用final修饰,他的生命周期和方法的生命周期是一样的,当方法弹栈,这个局部变量也会消失,那么如果局部内部类对象还没有马上消失想用这个局部变量,就没有了,如果用final修饰会在类加载的时候进入常量池,即使方法弹栈,常量池的常量还在,也可以继续使用

Java EE Fundamentals (27)/reflection, JDK new features

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.