Notes - Java Web Learning Tour

  • junit unit testing

    1. Black-box testing: No code is needed to give input values to see if the program can output the expected values.
    2. White-box testing: Some code is needed to focus on the specific execution process of the program.
  • Junit Use: White Box Testing

  • Steps:

    1. Define a test class (test case)

    2. Define test methods: They can run independently

    3. Annotate the method (@Test) (Annotation is required to run the method independently)

    4. Importing Junit's dependency environment

    5. Decision results:

      Red: Test failure

      Green: Successful Testing

      In general, we use assertions to process the result Asser. assertEquals (expected results, actual results);

      Plus: @Before:

      Modified methods are automatically executed before testing methods

      ​ @After:

      Modified methods are executed after test methods are executed

  • package cn.itcast.junit;
        //Caculator
    public class Calculator {
        public int add(int a,int b){
            return a+b;
        }
    
        public int sub(int a ,int b){
            return  a-b;
        }
    }
    
  • package cn.itcast.test;
    //You need to import the junit package to run the method independently
    import cn.itcast.junit.Calculator;
    import org.junit.After;
    import org.junit.Assert;
    import org.junit.Before;
    import org.junit.Test;
    
    /**
     * @Author: A
     * @Date: 2019/5/30 10:33
     * @Version 1.0
     * Test add method
     */
    public class CalculatorTest {
        /*
        * Initialization method
        * For resource applications, all test methods execute this method before execution
        * */
        @Before
        public void init(){
            System.out.println("init......");
        }
        /*
        * Method of releasing resources
        * After all test methods are executed, the method is executed
        * */
        @After
        public void close(){
            System.out.println("close...");
        }
        @Test
        public void testAdd(){
            //System.out.println("I'm executed");
            //Create calculator objects
            Calculator c = new Calculator();
            //Call the add method
           int result = c.add(1,2);
            System.out.println(result);
            //Assertion
            //The expected result is 2. The real result is not, the assertion fails.
            //Program console red
            Assert.assertEquals(3,result);
        }
    }
          //init......
          //3
          //close...
  • Reflection: the soul of frame design

    • Framework: Semi-finished software. Software development can be done on the basis of the framework to simplify the code.
    • Reflection: Encapsulating the components of a class into other objects is the reflection mechanism (the components include member methods, member variables, construction methods, etc.).
    • Reflection: It is through the class file object, to use the member variables in the file, construct methods, member methods.
  • How to get the Class object:
    1. Class.forName("full class name"): Load the bytecode file into memory and return the Class object
    2. Class Name. Class: Obtained by the class attribute of the class name
    3. Object. getClass()
  • //Class.forName("full class name")
    //Used mostly for configuration files
    Class cls1 = Class.forName("cn.itcast.domain.Person");
    
    //class name.class
    //Used mostly for parameter transfer
    Class cls2 = Person.class;
    
    //Object. getClass()
    //How to get bytecode mostly for objects
    Person p = new Person();
    Class cls3 = p.getClass();
  • Field: Membership variable

  • Common methods

  • 1. Setting value void set (Object obj, Object value)

  • 2. Getting the value get (Object obj) parameter requires passing the object.

  • 3. Security Check setAccessible(true) by Ignoring Access Permission Modifiers

  • Get member variables

  • package cn.itcast.reflect;
    //The next few classes to write for capturing functionality are related to this class
    
    public class Person {
        private String name;
        private int age;
        public String a;
        protected String b;
                String c;
        private String d;
    
        public Person() {
        }
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
    
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", a='" + a + '\'' +
                    ", b='" + b + '\'' +
                    ", c='" + c + '\'' +
                    ", d='" + d + '\'' +
                    '}';
        }
        public void eat(){
            System.out.println("eat....");
        }
        public void eat(String food){
            System.out.println("eat...."+food);
        }
    }
  • package cn.itcast.reflect;
    
    
    import java.lang.reflect.Field;
    
    public class ReflectDemo {
        public static void main(String[] args) throws Exception{
    
            //Get Person's Class es object
            Class personClass = Person.class;
            //Call the method getFields of the Class object to get member variables, and return an array of Field [] member variables
            //Get all public modified member variables
            Field[] fields = personClass.getFields();
            //To traverse fields, get each public modified member variable
            for(Field field :fields){
                System.out.println(field);
            }
            //Gets a public modifier member variable with the specified name
            //Field getField(String name)
            Field a =personClass.getField("a");
            //To get the value of the member variable a, we need to use the get(Object obj) method and pass the object parameters.
            Person p = new Person();
            Object value = a.get(p);
            System.out.println(value);//null
            //Set the value of member variable a
            a.set(p,"Zhang San");
            System.out.println(p);
            System.out.println("====================");
            //Get all member variables, regardless of modifiers
            Field[] declaredFields = personClass.getDeclaredFields();
            for(Field dec :declaredFields){
                System.out.println(dec);
            }
            //Gets a member variable with the specified name
            //Field getDeclaredField(String name)
            Field d =personClass.getDeclaredField("d");
            //Security checks for modifiers that ignore access permissions
            d.setAccessible(true);
            //Getting the value of member variables requires passing object parameters
            Object value2 = d.get(p);
            System.out.println(value2);
        }
    }
  • Constructor: Construction Method

  • Create objects: The T new Instance(Oject... initargs) parameter is the parameter type of the object construction method

  • If an object is created using an empty parameter constructor, the operation can be simplified: the newInstance method of the Class object

  • Acquisition construction method

  • package cn.itcast.reflect;
    
    import java.io.ObjectStreamClass;
    import java.lang.reflect.Constructor;
    
    public class ReflectDemo1 {
        public static void main(String[] args) throws Exception{
            //Get Person's Class es object
            Class personclass = Person.class;
            //Get the constructor fa of the Class object
            Constructor c =personclass.getConstructor(String.class,int.class);
            System.out.println(c);
            //The constructor is used to create objects.
            //Constructor has a method that newInstance can create objects
           Object person =  c.newInstance("Zhang San",22);
            System.out.println(person);
    
            //Create objects using empty parameter constructors
            Constructor c1 =personclass.getConstructor();
            System.out.println(c1);
            Object person1 =  c1.newInstance();
            System.out.println(person1);
            //The constructor of empty parameters can be created directly through the Class object method
            Object o = personclass.newInstance();
            System.out.println(o);
        }
    }
  • Getting member methods and classes
  • Method: Method object

  • Method of execution: Object invoke(Object obj,Object...args) needs to pass the real list of objects and parameters

  • Get the class name:

  • ​ String getName()

  • package cn.itcast.reflect;
    
    import java.lang.reflect.Method;
    
    public class ReflectDemo2 {
        public static void main(String[] args) throws Exception{
            //Get Person's Classs object, returning a Class class
            Class personClass  = Person.class;
            //Gets the specified Public member method
            //The name of the method needs to be passed, and the return value is the Method class
            Method eat_Method =personClass.getMethod("eat");
            Person p = new Person();
            eat_Method.invoke(p);//eat....
            //To get a member method with parameters, you need to pass the method name
            Method eat_method2 =personClass.getMethod("eat",String.class);
            //To get a method, you need to execute it.
            //Execution methods need to pass objects and parameters
            eat_method2.invoke(p,"meal");
    
    
            //Get all public methods
            Method[] allMethod = personClass.getMethods();
            for(Method method : allMethod){
                //Gets the name of the method getName();
                System.out.println(method.getName());
                System.out.println(method);
            }
    
            //Get class name
            String className=personClass.getName();
            System.out.println(className);//cn.itcast.reflect.Person
        }
    }
  • case

  • Requirement: Writing a framework that does not change any code for a class can help us create objects of any class and execute any of its methods

  • Steps:

    1. The full name of the object to be created and the method to be executed are defined in the configuration file.
    2. Loading and reading configuration files in programs
    3. Using Reflection Technology to Load Class Files into Memory
    4. create object
    5. Execution method
  • package cn.itcast.reflect;
    
    import java.io.InputStream;
    import java.lang.reflect.Method;
    import java.util.Properties;
    
    public class ReflectTest {
        public static void main(String[] args) throws Exception{
            //Loading configuration files
            //Create Properties Objects
            Properties pro = new Properties();
            //Get the Class bytecode file
            Class c = ReflectTest.class;
            //A class loader can be obtained by the method getClassLoader under bytecode file c
            ClassLoader cl = c.getClassLoader();
            //You can get a byte input stream from the required configuration file by using the method "getResourceAsStream (String name) under the Classloader class"
            //Passing parameters are files to be loaded to get byte input stream
           InputStream is= cl.getResourceAsStream("pro1.properties");
            //The Properties class method "load" (InputStream in Stream); "requires a byte input stream parameter
           //You can use the method load in the Properties collection to read the files saved in the hard disk into the collection for use.
           pro.load(is);//Configuration File Loading Completed
    
           //Get the data defined in the configuration file
            String className = pro.getProperty("className");
            String methodName=pro.getProperty("methodName");
    
            //Load this class into memory,
            Class cls= Class.forName(className);
            //Create objects that can be retrieved through the method newInstance in Class
           Object obj= cls.newInstance();
           //Gets the specified member method
            Method method = cls.getMethod(methodName);
            //The execution method needs to pass the object obj
            method.invoke(obj);
        }
    }
    //Seemingly understandable but not understandable... Understand or not understand... Do not understand............... Understand...
  • annotation

  • Definition: Annotation, also known as metadata, is a code-level description. It is a feature introduced by JDK 1.5 and later versions. It is at the same level as class and interface enumeration. It can be declared in front of package, class, field, method, local variable, method parameter, etc. to explain and annotate these elements.

  • Classification of roles:

    1. Writing Documents: Producing Documents by Annotation of Identifiers in Codes
    2. Code analysis: Analysis of code through annotations identified in the code
    3. Compilation Check: Enabling the compiler to perform basic compilation checks through annotations identified in the code
  • Some annotations scheduled in JDK

    1. @ Override: Does the method annotated by this annotation inherit from the parent class?

    2. @ Deprecated: The content of the annotation indicates that it has passed away

    3. @ Suppress Warnings: Suppressing Warnings

  • Custom Annotations

  • Format:

    Meta-annotations:

    Public@interface annotation name {}

    Essence: Annotations are essentially an interface that defaults to the Annotation interface

    Attributes: Membership methods can be defined in the interface

    The type of return value of an attribute

    1. Basic data class 2.String 3. Enumeration 4. Annotation 5. Arrays of the above types

    Define attributes and assign values to them when they are used

        1. If the default keyword is used to initialize the attribute by default when defining the attribute, the attribute assignment can be avoided when annotations are used.
    1. If only one attribute needs to be assigned and the name of the attribute is value, value can be omitted and the value can be defined directly.
      1. When assigning an array, the value is wrapped in {} and {} is omitted if there is only one value in the array.
  • Meta-annotations: Annotations used to describe annotations
  • @ Target: Describes where annotations work

    ElementType values: TYPE: can act on classes; METHOD: can act on methods FIELD: can act on member variables

    @ Retention: Describes the stages in which annotations can be retained

    @ Retention (Retention Policy, RUNTIME): The annotations currently described are retained in the class bytecode file and read by the JVM

    @ Documented: Describes whether annotations are extracted into api documents

    @ Inherited: Describes whether annotations are inherited by subclasses

  • package cn.itcast.reflect;
    public @interface Myanno2 {
    }
    
  • package cn.itcast.reflect;
    //Definition of enumeration class
    public enum Person2 {
        p1,p2;
    }
    
  • package cn.itcast.reflect;
    
    
    public @interface Myanno {
        //Types that annotations can return
        // 1. Basic data class 2. String 3. Enumeration 4. Annotation 5. Arrays of types above
        int show1();
        public abstract String show2() default "Zhang San";
        public abstract Person2 per();
        Myanno2 anno2();
        //String[] strs();*/
    
    }
    
  • package cn.itcast.reflect;
    //The return value of String type has been modified by default to avoid assigning attributes
    @Myanno(show1=1,per=Person2.p1,anno2=@Myanno2)
    public class Worker {
    }
    
  • Note case exercises

  • package cn.itcast.reflect;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Check {
    }
    
  • package cn.itcast.reflect;
    
    public class Calculator {
        //addition
        @Check
        public void add(){
            System.out.println("1+0="+(1+0));
        }
        //subtraction
        @Check
        public void sub(){
            System.out.println("1-0="+(1-0));
        }
        //multiplication
        @Check
        public void mul(){
            System.out.println("1*0="+(1*0));
        }
        //division
        @Check
        public void div(){
            System.out.println("1/0="+(1/0));
        }
        public void show(){
            System.out.println("Never bug");
        }
    }
    
  • package cn.itcast.reflect;
    
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.lang.reflect.Method;
    
    /**
     * Simple test framework
     * When the main method is executed, all methods are automatically detected (Check annotated methods)
     */
    
    public class TestCheck {
        public static void main(String[] args) throws IOException {
            //Create calculator objects
            Calculator c = new Calculator();
            //Get the bytecode file
           Class cls = c.getClass();
           //Get all the methods
            Method[] methods = cls.getMethods();
            int number =0;//Number of abnormalities
            BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));
    
            for(Method method : methods){
                //Judging whether there are Check annotations in the method
                if(method.isAnnotationPresent(Check.class)){
                    //Yes, execution.
                    try{
                        method.invoke(c);
                    }catch (Exception e){
                        //Capture exception
                        //Record to file
                        number++;
                        bw.write("The method is abnormal.");
                        bw.newLine();
                        bw.write("Exception name:"+e.getCause());
                        bw.newLine();
                        bw.write("Causes of anomalies"+e.getCause().getMessage());
                        bw.newLine();
                        bw.write("--------------------");
                        bw.newLine();
                    }
                    bw.write("The test came out altogether."+number+"Secondary anomaly");
                    bw.flush();
                }
            }
        }
    }
    
/*
* There were 0 abnormalities in this test. There were 0 abnormalities in this test.
Exception name: java.lang.ArithmeticException: / by zero
 Causes of anomalies / by zero
--------------------
There was a total of one abnormality in this test. There was a total of one abnormality in this test.
/

Keywords: PHP Java Junit calculator Attribute

Added by webwired on Thu, 30 May 2019 21:10:13 +0300