26th Day Notes

Source: Internet
Author: User

Dark Horse programmer <a href= "http://www.itheima.com" target= "blank" >java training </a>

26th Day Notes

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.
1) 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.
2) 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
3) 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 (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
Extensionclassloader 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
Sysetmclassloader 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 configuration file example)
Juice Extractor (Juicer) Case of juicing
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 { Public voidsqueeze (); }                classAppleImplementsFruit { Public voidsqueeze () {System.out.println ("Squeeze out a cup of apple juice."); }        }                classOrangeImplementsFruit { Public voidsqueeze () {System.out.println ("Squeeze out a glass of orange juice."); }        }                classJuicer { Public voidrun (Fruit f) {f.squeeze (); }                }


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


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 (Get method by reflection and use)
Method
Class.getmethod (String,class ...) and Class.getdeclaredmethod (String, Class ...) The Object,object method can get the specified method in the class, Invoke Invoke (...) 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<integer> 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 Voidsetproperty (Object obj, String PropertyName, Object value) {}, which sets the value of the property named PropertyName in the Obj object to values.

10_ Reflex (practice)
A class is known to be 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.

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: Spring 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 objectnewproxyinstance (ClassLoader loader,class<?>[] Interfaces,invocationhandler h)
The method that will eventually call Invocationhandler
Invocationhandlerobject Invoke (Object Proxy,method method,object[] args)

12. Design pattern (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


13.jdk5 new Feature (self-implementing enum 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: 7 days a week, only 12 months a year.
B: Recall a 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.

14.jdk5 new features (Considerations for enumerations)
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. The use of enumeration items is special: enumeration ("");
An enumeration class can also have an abstract method, but an enumeration item must override the method
Use of enumerations in a switch statement

15.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> tvalueof (class<t> 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

16.jdk7 new Features (review and explanation of the six new features of JDK7)
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

17.jdk8 new Features (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.

26th Day Notes

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.