1. Junit Unit Testing
1. Background:
The problem with writing code test in main method is that all code is written in main method and will run. If we want to test, we will execute all code and the test efficiency will be lower.
2. Concept:
Unit testing is testing part of the content.
Junit is a third-party unit testing framework in java, which is stored in junit.jar.
PS: First party: classes provided by JDK; second party: classes written by oneself; third party: many classes written by others.
junit usage: part of the code can be tested
3. Use steps of Junit
1. Define a test class 2. Writing test methods Requirements for testing methods: 1 must be public modified 2 The return value must be void 3 parameter list must be empty 3. Write the code we want to test in the test method 4. Add an @Test annotation to the test method header 5. Running test methods 5.1 Mode of Operation 5.1.1 On the left side of the test method, click on the green triangle and run a test method. 5.1.2 On the left side of the test class, click on the green triangle to run the test method in a class. 5.1.3 Right-click on the package, click on the green triangle, and run the test methods for all the classes in the package. 5.2 Running results: 5.2.1 Green means pass 5.2.2 Red means no passage 5.2.3 Yellow means [assertion] is problematic
Assert. assertEquals
public class Test01 { @Test public void test01() { // 3. Write the code we want to test in the test method System.out.println("I am the test method."); // int a = 10 / 0; // Testing the functionality of your own classes Calcuate calc = new Calcuate(); int sum = calc.sum(1, 3); System.out.println("sum = " + sum); // Assertion: Let's see if our guess is the same as the real one. // Assert. assertEquals (guess value, real value); Assert.assertEquals(4, sum); } }
4. Common Annotations of Junit
The function of four annotations (there are no triangles on the left of the following four, which run automatically) @ Before: Execute before each test method @ After: Execute after each test method @ BeforeClass: Execute before all test methods @ AfterClass: Execute after all test methods
public class Test02 { @BeforeClass public static void testBeforeclass22() {//To add static statc modifiers System.out.println("BeforeClass"); } @AfterClass public static void testAfterClass22() {//To add static statc modifiers System.out.println("AfterClass"); } @Before public void testBefore22() { System.out.println("Before"); } @After public void testAfter22() { System.out.println("After"); } @Test public void test01() { System.out.println("I am the test method."); } @Test public void test02() { System.out.println("I am the test method."); } }
5. The use of junit requires importing two jar packages
hamcrest-core-1.3.jar and junit-4.12.jar
2. Reflection
1. Class object
1. Concept:
The class name is Class, the object created by this Class class, which we call Class object. A class has only one class object. Often named clazz or cls
public final class Class<T> { // Membership variables // Membership method }
2. Production process and function
(1) Process
Before JDK 1.8:
When the. class file is loaded into the method area in memory, the JVM creates a Class object, which stores the information of the member variables, member methods and construction methods in the class file.
After JDK 1.8:
Compared with JDK 1.8, there is no method area but metaspace. The class object created is placed in metaspace, but controlled by OS (Operating System) instead of JVM.
(2) Role
Class objects are d objects that must be used for reflection (because getting a Class object is equivalent to getting everything in the class)
3. Three Methods of Obtaining class Objects
1. class name. 2. Object name. getClass() 3. Class. forName (full name of class); full name of class is package name. class name
Note: In future work, use the third way, because it uses the full name of the class, belongs to the string, flexible.
A class has only one class object
public class Demo04 { public static void main(String[] args) throws ClassNotFoundException { // 1. class name. Class<Employee> cls1 = Employee.class; System.out.println(cls1); //Rewrite the toString method class com.itheima.bean.Employee // package name. class name // 2. Object name. getClass() Employee e = new Employee();//The generic type of the next sentence is up-bound because it is possible that the new statement is a subclass of Employee, that is, polymorphism. Class<? extends Employee> cls2 = e.getClass(); System.out.println(cls2); // 3. Class. forName (full name of class); Class<?> cls3 = Class.forName("com.itheima.bean.Employee");//Click on the Employee class - > copy Reference System.out.println(cls3); //Explain that the class object obtained by the above three methods is the same object (that is, a class has only one class object) System.out.println(cls1 == cls2); // true System.out.println(cls1 == cls3); // true } }
4. Methods in Class Classes
Method of Obtaining Class Object Information (2) String getName(); Get the full name of the class String getSimpleName(); Get [class name] Object newInstance(); create objects
public class Demo05 { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException { Class<?> cls = Class.forName("com.itheima.bean.Employee"); // String getName(); Gets the full name of the class String name = cls.getName(); System.out.println("name = " + name); // com.itheima.bean.Employee // String getSimpleName(); Gets the class name String simpleName = cls.getSimpleName(); System.out.println("simpleName = " + simpleName); // Employee // Object newInstance(); create objects Object obj = cls.newInstance(); // Employee = new Employee (); (that is, the method actually creates an object of the class Employee) System.out.println(obj); } }
2. Reflection
1. Concept:
When the program runs, it obtains the constructor, member method and member variable in the class through the Class object, and operates on them. (Anatomizing the class)
2. Application scenarios:
Intelligent Tips and Framework of IDEA Software
3. The steps of reflection:
1. Getting Class Objects
2. Call method operation corresponding content
4. Reflection acquisition and operation construction method
(1) Constructor class
Construction methods in presentation classes
(2) Get the Constructor object of public
Steps:
1. Get the Class object
2. The Constructor object is obtained by the method of Class object, as follows:
getConstructors: Get all the public constructions getConstructor: Get a construction method of public
(3) The declared Constructor object
The declared Constructor object refers to all construction methods in the original class.
Steps:
1. Get the Class object
2. Constructor to be declared by means of method
GetDeclared Constructors: Get the construction method of all declarations GetDeclared Constructor: Getting a declarative constructor
PS: Declared has been declared, regardless of authority, no Declared has been published.
(4) Method of Constructor class (use the constructed method):
Object newInstance(...);
See Code 1: Integer. class!= int. class
b. See Code 2: For private constructors obtained through declarative means, we must call the following methods before using them.
Violent reflex setAccessible(true);
public class Demo061 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { // 1. Get the Class object Class<?> cls = Class.forName("com.itheima.bean.Employee"); // 2. Getting Constructor Object by Class Object Method // getConstructors Get All the Construction Methods of public /*Constructor<?>[] constructors = cls.getConstructors(); for (Constructor<?> c : constructors) { System.out.println("c = " + c); }*/ // GettConstructor Gets a Construction Method of public Constructor<?> c1 = cls.getConstructor(); System.out.println("c1 = " + c1); // public com.itheima.bean.Employee() Object obj1 = c1.newInstance();//It's equivalent to creating an Employee object System.out.println("obj1 = " + obj1);//obj1 = Employee{name='null', age=0, weight=0.0, height=0.0} Constructor<?> c2 = cls.getConstructor(String.class, int.class);//Class object Integer. clas!= int. class, which refers to basic data type and reference data type, does not write Integer System.out.println("c2 = " + c2); // public com.itheima.bean.Employee(java.lang.String,int) Object obj2 = c2.newInstance("Miss Luo Yu Feng", 18);//It's equivalent to creating an Employee object System.out.println("obj2 = " + obj2);//obj2 = Employee{name='Feng Jie', age=18, weight=0.0, height=0.0} } }
public class Demo062 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { // 1. Get the Class object Class<?> cls = Class.forName("com.itheima.bean.Employee"); // 2. Constructor that gets the declaration by means of method // GetDeclared Constructors: Get the construction method of all declarations Constructor<?>[] declaredConstructors = cls.getDeclaredConstructors(); /*for (Constructor<?> c : declaredConstructors) { System.out.println("c = " + c); }*/ // GetDeclared Constructor: Getting a declarative constructor Constructor<?> c1 = cls.getDeclaredConstructor(String.class); System.out.println("c1 = " + c1); // private com.itheima.bean.Employee(java.lang.String) // For private methods, we need to react violently before using them. c1.setAccessible(true); // Settings can be accessed to true Object obj1 = c1.newInstance("Miss Luo Yu Feng"); System.out.println("obj1 = " + obj1); } }
5. Reflect to get and manipulate member methods
(1) Method class
Common methods in presentation classes
(2) Getting Method Objects
1. Get the Class object
2. Call the method of Class object to get the Method object
getMethods: Get all public methods, including the parent getMethod: Get a public method GetDeclared Methods: A way to get all declarations GetDeclared Method: Get a declared method
(3) Method class methods (using the resulting member methods):
Object invoke(Object obj, Object... args) Object obj: Objects that call methods Object... args: Parameters passed to a method when calling a method Object Return value: This is the return value of this method.
public class Demo07 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException { // 1. Get the Class object Class<?> cls = Class.forName("com.itheima.bean.Employee"); Object obj = cls.newInstance(); // 2. Call the method of Class object to get the Method object // getMethods: Get all public methods, including parent classes (such as Object classes) // Method[] methods = cls.getMethods(); // for (Method m : methods) { // System.out.println("m = " + m); // } // getMethod: Get a public method Method m1 = cls.getMethod("setName", String.class); System.out.println("m1 = " + m1); Object r1 = m1.invoke(obj, "Miss Luo Yu Feng"); System.out.println("Return value 1 = " + r1);//This method does not return a value, so it prints out null. System.out.println(obj);//Printed out is an object's information indicating that the method has been executed. // GetDeclared Methods: The method of getting all declarations (there will be no more methods of parent classes such as Object classes printed out at this time) // Method[] declaredMethods = cls.getDeclaredMethods(); // for (Method m : declaredMethods) { // System.out.println("m = " + m); // } // GetDeclared Method: Get a declared method Method m2 = cls.getDeclaredMethod("sleep", int.class); m2.setAccessible(true);//Method Private, Violent Reflex Object r2 = m2.invoke(obj, 8); System.out.println("Return value 2 = " + r2); } }
6. Obtaining and manipulating member variables by single shot
(1) Filed class
Represents member variables in a class
(2) Getting Filed Objects
1. Getting Class Objects
2. Call the method of Class object to get Field object
getFields: Gets all public member variables getField: Gets a public member variable GetDeclared Fields: Gets all declared member variables getDeclaredField: Gets a declared member variable
(3) Filed class methods (use the resulting member variables) - - - -- - > less used, Method and Structurer are commonly used in reflection
Membership variables are used to set values/get values
Set values: Basic data types: setXxx (Object obj, Xxx), e.g. setDouble(Object obj, double d), * setInt(Object obj, int i) Reference data type: set(Object obj, Object arg) Get the value: Basic data type: getXxx(Object obj). For example: getDouble()/getInt() Reference data type: get(Object obj);
public class Demo08 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException { // 1. Getting Class Objects Class<?> cls = Class.forName("com.itheima.bean.Employee"); Object obj = cls.newInstance(); // 2. Calling Class Object's Method to Get Field Object // getFields: Gets all public member variables /*Field[] fields = cls.getFields(); for (Field f : fields) { System.out.println("f = " + f); }*/ // getField: Gets a public member variable Field f1 = cls.getField("weight"); System.out.println("f1 = " + f1); f1.setDouble(obj, 66.6); System.out.println("obj = " + obj); System.out.println(f1.getDouble(obj)); // GetDeclared Fields: Gets all declared member variables // Field[] declaredFields = cls.getDeclaredFields(); // for (Field f : declaredFields) { // System.out.println("f = " + f); // } // getDeclaredField: Gets a declared member variable Field f2 = cls.getDeclaredField("name"); System.out.println("f2 = " + f2); f2.setAccessible(true); f2.set(obj, "Flowery"); System.out.println("obj = " + obj); System.out.println(f2.get(obj)); // Get the type of member variable Class<?> type = f2.getType();//The return value is a class object System.out.println(type.getName());//Get the full name of the class System.out.println("type: " + type.getSimpleName());//To get the class name, use the getSimpleName method( } }
7. Reflective applications (where are the advantages?)
Create different objects and call methods according to different class and method names in the configuration file.
1. Define students/teachers, etc. 2. Create a configuration file config.properties // Because reflection changes the class name into a class object, it writes the full class name. // At the same time, the name can not appear in Chinese, there will be errors. 2.1 Configuration class name 2.2 Configuration Method Name 3. Loading properties data into Properties objects 4. Getting Class Objects by Class Name 5. Method acquisition based on method name 6. Using Reflection Execution Method
public class Demo09 { public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException { // 3. Loading properties data into Properties objects Properties pp = new Properties(); pp.load(new FileInputStream("day12demo/config.properties")); System.out.println("pp = " + pp); // {classname=com.itheima.demo09Reflect.Student, methodname=study} String classname = pp.getProperty("classname"); // com.itheima.demo09Reflect.Student String methodname = pp.getProperty("methodname"); // study // 4. Getting Class Objects by Class Name Class<?> cls = Class.forName(classname); Object obj = cls.newInstance(); // 5. Method acquisition based on method name Method method = cls.getMethod(methodname); // 6. Using Reflection Execution Method method.invoke(obj); } }
The benefits of reflection are reflected in the above code:
Reflection reduces coupling and improves the flexibility and extensibility of code. (Applications such as: Framework)
(In this case, you don't need to modify the internal code, you just need to modify a little configuration file information to get the results of different methods of execution.)
3. Annotations
1. Concept:
Annotation is a new feature of JDK 1.5. The essence of the annotation is to save some data.
Annotations add additional information to classes, and they are used by java compilers and JVM virtual machines (for programs)
2. Role:
Writing Documents: Generating Documents by Annotations identified in the Code [Generating Documents Documents] Compilation Check: The basic compilation check can be implemented by the compiler through annotations identified in the code. Code analysis: Analysis of code through annotations identified in the code [using reflection]
3. Custom Annotations
(1) Format
Custom annotation format: @ interface annotation name{ // Annotation attributes Data type variable name (); }
There are four types of attributes for annotations:
All 1.8 basic data types are available 2.String, Enumeration, Annotation, Class 3. One-dimensional arrays of the above types 4. String and lass in the Class can
Note: Since annotations are meant to transfer some lightweight, small data, they don't support as many types as they do. So custom types are not good for annotations (such as Integer, custom student classes, etc.)
(2) Use
You must assign values when you use them, and each attribute must have values, otherwise you will compile errors.
@ Annotation name (attribute name = attribute value, attribute name = attribute value)
Special circumstances:
(1) When you customize annotations, you can set default values for their properties. Annotations whose properties are set to default values can be used without assignment and compiled without assignment and without error.
(2)
a. When there is only one attribute in the annotation and the attribute name is value: when using the annotation, the attribute name value can be omitted
b. When there are multiple attributes in the annotation, and one attribute name is value, and the other attribute values have default values: when using the annotation, the attribute name value can be omitted.
public @interface MyAnno2 { // attribute String name(); double price() default 18.8; // Default values String[] authros(); // WeekDay weekDay(); // Enumeration can // MyAnno1 mya(); // Annotation can be // Class cls(); // Class can } enum WeekDay { SUN, MON }
4. Meta-annotations
(1) Concept:
Annotations embellishing annotations
(2) @Target meta-annotation
Function: Restrict the location of annotations (PS: When the meta-annotation is not used, the default is where the annotation can be used)
@Target(ElementType.TYPE) // Let annotations be used on classes or interfaces @Target(ElementType.CONSTRUCTOR) // Make annotations usable in construction methods @Target(ElementType.METHOD) // Make annotations usable in common ways @Target(ElementType.FIELD) // Let annotations be used on member variables @Target(ElementType.LOCAL_VARIABLE) // Let annotations be used on local variables
(3) @Retention meta-annotation
Function: Limit when annotations can survive (PS: Default annotations live to CLASS without using the meta-annotation)
@Retention(RetentionPolicy.RUNTIME)//RUNTIME phase @Retention(RetentionPolicy.CLASS)//CLASS phase @Retention(RetentionPolicy.SOURCE)//SOURCE phase
SOURCE phase CLASS phase RUNTIME phase Java (source code) - > compile - > class - > run
5. Annotation Analysis
1. Concept:
When the program runs, get the attribute values in the annotations
2. Annotated Element Interface
AnnotatedElement interface defines the method of parsing annotations
T get Annotation (Class < T > annotation Class) Gets a single annotation on an object Annotation[] getAnnotations() Gets all annotations on an object Boolean is AnnotationPresent (Class annotation Class) determines whether there is this annotation
Note: Class, Constructor, Method, Field and other writings implement AnnotatedElement interfaces.
3. How to Analyse Annotations
Annotations are available to whoever they are If annotations are constructed, use Constructor to obtain them If annotations are on member methods, use Method to get them If annotations are on member variables, use Field to get them
Definition Notes:
// annotation @Retention(RetentionPolicy.RUNTIME)//Write, otherwise the annotation will only live to the default stage class, and the runtime will not get the annotation content. public @interface BookAnno { String color(); double price(); }
Book class
public class Book { @BookAnno(color = "Yellow", price = 0.99) private String name; @MyAnno4 @BookAnno(color = "Green", price = 99) // Data on annotations can be parsed anywhere (flexible) public void sale(String color, double price) { // Data on method parameters can only be obtained in this method. } }
public class Demo13 { // Let's click on the green triangle on the left and the program runs. public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // Obtaining annotations on Methods // 1. Getting Class Objects Class<?> cls = Class.forName("com.itheima.demo14 Annotation Analysis_Practice.Book"); // 2. Obtaining Method Objects by Reflection Method sale = cls.getMethod("sale"); // 3. Analytical Annotations // Boolean is AnnotationPresent (Class annotation Class) determines whether there is this annotation boolean b = sale.isAnnotationPresent(BookAnno.class); System.out.println("b = " + b); //if statement: first judge whether there are annotations, then obtain annotations if (b) {//Write b==false for judgment condition BookAnno anno = sale.getAnnotation(BookAnno.class); System.out.println(anno.color() + ":" + anno.price()); } // Annotation[] getAnnotations() Gets all annotations on an object Annotation[] annos = sale.getAnnotations(); for (Annotation a : annos) { System.out.println("a = " + a); } } // unit testing @Test public void test02() throws Exception { Class<?> cls = Class.forName("com.itheima.demo14 Annotation Analysis_Practice.Book"); Field name = cls.getDeclaredField("name"); Annotation[] as = name.getAnnotations(); for (Annotation a : as) { System.out.println("a = " + a); } } }
Simulate JUnit's @Test annotations and automatically run the method with @Test annotations
// 1. Custom MyTest annotations @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyTest { }
// 2. Customize a class and configure MyTest annotations for some methods public class Person { public void getUp() { System.out.println("Wake up"); } @MyTest public void eat() { System.out.println("Time to have a meal"); } public void study() { System.out.println("Learn"); } @MyTest public void sleep() { System.out.println("Sleep"); } }
public class Demo15 { public static void main(String[] args) throws Exception { // 3. Analytical Notes: // 3.1 Get Class Objects Person s = new Person(); Class<?> cls = Class.forName("com.itheima.demo15 Annotation case_simulation Junit.Person"); // 3.2 Get all the methods Method[] methods = cls.getMethods(); for (Method method : methods) { // 3.3 Run this method if there are annotations on the Method if (method.isAnnotationPresent(MyTest.class)) { method.invoke(s); } } } }
Class loader records class files in memory
4. Dynamic Agent
1. Real life agency
Ticket Selling Interface The function of selling tickets You buy train tickets - > cattle - > 12306 You Buy Computer - > Computer Agent - > Shenzhou Factory Implementation of Ticket Selling Interface between Cattle and 12306
Four Elements of Agency Model
Caller: You Real objects: objects that actually call functions (12306) Proxy objects: objects between callers and real objects (scalpers) Abstract object: interface between proxy object and real object
2. Dynamic Agent:
In the process of program running, agent objects are created dynamically
3. Benefits of Agent Model
Functions of real objects can be enhanced without changing the real object code, and methods can be intercepted (see the following case)
4. Dynamic proxy API
Proxy class: Proxy is translated into proxy, one of its methods is as follows:
// Create a proxy object static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) ClassLoader loader // class loader Class <?>[] interfaces // interface array, and the created proxy object implements these interfaces InvocationHandler h// Execution Processor (an interface) is an implementation class object or an anonymous internal class (rewriting invoke method) when a method is called as a method parameter. When the method of the proxy object is executed, the invoke method of the object is executed. Object // Return Value: The created proxy object Summary: Object proxy object = Proxy. newProxyInstance (class loader, interface, execution processor);
5. Process Details
Proxy.newProxyInstance: Create a proxy object. The proxy object implements the interface specified by the parameter (the second parameter) (the list interface is implemented in this case, so that the proxy object in this case has the same function (method) as ArryList. When a proxy object calls a method, it calls the overridden invoke method of the execution processor InvocationHandler, which can be either enhanced or intercepted when overridden.
case
/* Case objectives: Use dynamic proxy to enhance all methods of ArrayList and count the time spent on each method call of ArrayList ArrayList Is the real object main Method as caller The proxy object is the daiLi object we created The abstract object implements the InvocationHandler() interface when we create the daiLi object */ public class Demo16 { public static void main(String[] args) { // Creating Real Objects ArrayList<String> arrayList = new ArrayList<>(); // Class object can get class loader // A proxy object is created, which implements the interface specified by parameters. List daiLi = (List) Proxy.newProxyInstance(Demo16.class.getClassLoader(), new Class[]{List.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { /* Object proxy: Proxy objects, generally not processed Method method: Called method Object[] args: Parameters when calling methods */ // System. out. println ("invoke:"+method. getName ()+", parameter: +Arrays.toString(args)); // Record start time before invocation long start = System.currentTimeMillis(); Object re = null;//Avoid the last return; the scope of the statement is insufficient // Interception method (no remove method is used for callers) if (method.getName().equals("remove")) { System.out.println("Lao Tzu does nothing!"); return false; } else { // Call the method of the real object, what method the proxy object calls, and what method the real object calls. re = method.invoke(arrayList, args); } // Recording time after invocation long end = System.currentTimeMillis(); System.out.println(method.getName() + " Time-consuming: " + (end - start)); return re;//What does an object return? What does a proxy object return? } }); daiLi.add("aa"); // When the method of the proxy object is called, invoke to the execution processor is executed daiLi.add("bb"); daiLi.add("cc"); daiLi.add("dd"); daiLi.remove("bb"); daiLi.set(0, "Miss Luo Yu Feng"); System.out.println("arrayList: " + arrayList); } }
if (method.getName().equals("remove")) { System.out.println("Lao Tzu does nothing!"); return false; } else { // Call the method of the real object, what method the proxy object calls, and what method the real object calls. re = method.invoke(arrayList, args); } // Recording time after invocation long end = System.currentTimeMillis(); System.out.println(method.getName() + " Time-consuming: " + (end - start)); return re;//What does an object return? What does a proxy object return? } }); daiLi.add("aa"); // When the method of the proxy object is called, invoke to the execution processor is executed daiLi.add("bb"); daiLi.add("cc"); daiLi.add("dd"); daiLi.remove("bb"); daiLi.set(0, "Miss Luo Yu Feng"); System.out.println("arrayList: " + arrayList); }
}