Notes -JavaWeb learning journey

  • junit unit test

    1. Black box testing: no need to write code to the input value to see if the program can output a desired value
    2. White-box testing: need some code, the program concerns the specific implementation process
  • Junit use: white box

  • Steps:

    1. Define a class test (test)

    2. Define the test: You can run independently

    3. Method to add annotations (@Test) (need to add annotations can run independently method)

    4. Junit introduced environment-dependent

    5. judgement result:

      Red: the test fails

      Green: the test is successful

      Generally, we use assertions to process the results Asser.assertEquals (the desired result, actual results);

      Supplementary: @Before:

      Modified method will be automatically executed before the test method

      ​ @After:

      Modified method will be executed after test execution method

  • package cn.itcast.junit;
        //计算器类
    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;
    //需要导入junit包,才可以独立运行方法
    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
     * 测试add方法
     */
    public class CalculatorTest {
        /*
        * 初始化方法
        * 用于资源申请,所有测试方法在执行之前都会先执行此方法
        * */
        @Before
        public void init(){
            System.out.println("init......");
        }
        /*
        * 释放资源方法
        * 在所有测试方法执行完毕后,都会执行该方法
        * */
        @After
        public void close(){
            System.out.println("close...");
        }
        @Test
        public void testAdd(){
            //System.out.println("我被执行了");
            //创建计算器对象
            Calculator c = new Calculator();
            //调用add方法
           int result = c.add(1,2);
            System.out.println(result);
            //断言
            //我期望的结果是2,真实结果不是,断言失败
            //程序控制台出现红色
            Assert.assertEquals(3,result);
        }
    }
          //init......
          //3
          //close...
  • Reflection: Design frame Soul

    • Frame: semi-finished software. Software can be developed on the base frame, to simplify the code
    • Reflection: The various components of the package as the other objects of the class, which is the reflection (including part of the member methods, member variables, configuration method, etc.)
    • Reflection: through class file object member variables to use, construction method, the method of the file members.
  • Gets the Class object of ways:
    1. Class.forName ( "full class name"): the bytecode file loaded into memory, the object return Class
    2. Class name .class: acquiring attribute class by class name
    3. Object .getClass ()
  • //Class.forName("全类名")
    //多用于配置文件
    Class cls1 = Class.forName("cn.itcast.domain.Person");
    
    //类名.class
    //多用于参数的传递
    Class cls2 = Person.class;
    
    //对象.getClass()
    //多用于对象的获取字节码的方式
    Person p = new Person();
    Class cls3 = p.getClass();
  • Field: member variables

  • Common method

  • 1. Set values ​​void set (Object obj, Object value)

  • 2. Get the value get (Object obj) parameters need to pass an object,

  • 3. Ignore access modifier security checks setAccessible (true)

  • Acquiring member variables

  • package cn.itcast.reflect;
    //接下来要写的几个获取功能的类都与此类有关联
    
    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{
    
            //获取Person的Class对象
            Class personClass = Person.class;
            //调用Class对象的方法getFields获取成员变量,返回的是Field[] 成员变量的数组
            //获取所有的public 修饰的成员变量
            Field[] fields = personClass.getFields();
            //对fields遍历,获取每一个public修饰的成员变量
            for(Field field :fields){
                System.out.println(field);
            }
            //获取指定名称的public 修饰的成员变量
            //Field getField(String name)
            Field a =personClass.getField("a");
            //获取成员变量a的值,需要使用get(Object obj)方法,需要传递对象参数
            Person p = new Person();
            Object value = a.get(p);
            System.out.println(value);//null
            //设置成员变量a的值
            a.set(p,"张三");
            System.out.println(p);
            System.out.println("====================");
            //获取所有的成员变量,不考虑修饰符
            Field[] declaredFields = personClass.getDeclaredFields();
            for(Field dec :declaredFields){
                System.out.println(dec);
            }
            //获取指定名称的成员变量
            //Field getDeclaredField(String name)
            Field d =personClass.getDeclaredField("d");
            //忽略访问权限的修饰符的安全检查
            d.setAccessible(true);
            //获取成员变量的值,需要传递对象参数
            Object value2 = d.get(p);
            System.out.println(value2);
        }
    }
  • Constructor: Constructor

  • Create an object: T new Instance (Oject ... initargs) parameter is a parameter of type Object constructor

  • If you create an object with an empty argument constructor, the operation can be simplified: newInstance Class object methods

  • Obtaining 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{
            //获取Person的Class对象
            Class personclass = Person.class;
            //获取Class对象的构造方fa
            Constructor c =personclass.getConstructor(String.class,int.class);
            System.out.println(c);
            //构造方法用来创建对象的,
            //Constructor 有个方法newInstance可以创建对象
           Object person =  c.newInstance("张三",22);
            System.out.println(person);
    
            //使用空参数构造器创建对象
            Constructor c1 =personclass.getConstructor();
            System.out.println(c1);
            Object person1 =  c1.newInstance();
            System.out.println(person1);
            //可以通过Class对象方法直接创建空参数的构造器
            Object o = personclass.newInstance();
            System.out.println(o);
        }
    }
  • The method of obtaining a member of the class
  • Method: Method Object

  • Execution method: Object invoke (Object obj, Object ... args) need to pass the real object and the parameter list

  • 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{
            //获取Person的Class对象,返回的是一个Class类
            Class personClass  = Person.class;
            //获取指定的Public成员方法
            //需要传递方法的名称,返回值是Method类
            Method eat_Method =personClass.getMethod("eat");
            Person p = new Person();
            eat_Method.invoke(p);//eat....
            //获取有参数的成员方法,需要传递方法名称
            Method eat_method2 =personClass.getMethod("eat",String.class);
            //获取到方法,就要执行方法
            //执行方法,需要传递对象和参数
            eat_method2.invoke(p,"饭");
    
    
            //获取所有public 方法
            Method[] allMethod = personClass.getMethods();
            for(Method method : allMethod){
                //获取方法的名称getName();
                System.out.println(method.getName());
                System.out.println(method);
            }
    
            //获取类名
            String className=personClass.getName();
            System.out.println(className);//cn.itcast.reflect.Person
        }
    }
  • Case

  • Requirements: write a framework, under the premise of not changing any code to the class, you can help us create objects of arbitrary classes, and perform any of the method

  • step:

    1. The full class name of the object you need to create and define the methods to be executed in the configuration file
    2. In the program reads the configuration file is loaded
    3. Using the reflection technique to load the 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{
            //加载配置文件
            //创建Properties对象
            Properties pro = new Properties();
            //获得Class字节码文件
            Class c = ReflectTest.class;
            //通过字节码文件c下的方法getClassLoader  可以获得一个类加载器
            ClassLoader cl = c.getClassLoader();
            //可以通过Classloader类下的方法“getResourceAsStream​(String name)”可以找到需要的配置文件获得一个字节输入流
            //传递的参数为要加载的文件,获取字节输入流
           InputStream is= cl.getResourceAsStream("pro1.properties");
            //Properties 类的方法 “load​(InputStream inStream);”需要一个字节输入流的参数
           //可以使用Properties集合中的方法load,把硬盘中保存的文件,读取到集合中使用
           pro.load(is);//配置文件加载完成
    
           //获取配置文件中定义的数据
            String className = pro.getProperty("className");
            String methodName=pro.getProperty("methodName");
    
            //加载该类进内存,
            Class cls= Class.forName(className);
            //创建对象,可以通过Class中的方法newInstance来获取
           Object obj= cls.newInstance();
           //获取指定的成员方法
            Method method = cls.getMethod(methodName);
            //执行方法,需要传递对象obj
            method.invoke(obj);
        }
    }
    //似懂非懂……懂非懂…………非懂………………懂…………
  • annotation

  • Definition: Notes (Annotation), also known as metadata a code-level description, he is a characteristic JDK1.5 and later introduced the classes, interfaces, enumerations are on the same level, he can be declared in the package, the foregoing classes, fields, methods, local variables, parameters and the like of the method for these elements will be described, Note

  • Role Category:

    1. Writing documentation: annotated document production by the identifier code
    2. Code analysis: analysis of the code by annotating code identified
    3. Compile check: by annotating code identified so that the compiler can compile basic checks
  • JDK in a predetermined number of notes

    1. @Override: to detect the marked whether the comment is inherited from the parent class

    2. @Deprecated: This comment marked content, that has passed away

    3. @SuppressWarnings: suppress warnings

  • Custom annotation

  • format:

    Yuan notes:

    {} public @interface annotation name

    Essence: annotation is essentially a interface that inherits default Annotation Interface

    Properties: Interface members can be defined method

    Property return type

    1. The basic data type enumeration 2.String 3. 4. 5. annotation array of more than one type of

    Defines the properties, give the property assignment in the use

        1. 如果定义属性时,使用default关键字给属性默认初始化值,则使用注解时,可以不就行属性的赋值
    1. If there is only a need to assign attribute, and value is the name of the property, the value may be omitted, the value can be defined directly
      1. Assigning an array using {value} package, if there is only one value of the array {omitted}
  • Annotations are used to describe annotation: a meta-annotation
  • @Target: annotation can describe the role of location

    ElementType Value: TYPE: can be at class; METHOD: The method can be applied to the FIELD: can be applied to the member variables

    @Retention: Phase Description Notes can be reserved

    @Retention (RetentionPolicy, RUNTIME): the current annotation to be described, will be retained to the class bytecode files, and read into the JVM

    @Documented: description notes whether the document is drawn into the api

    @Inherited: description notes whether inherited by subclasses

  • package cn.itcast.reflect;
    public @interface Myanno2 {
    }
    
  • package cn.itcast.reflect;
    //枚举类的定义
    public enum Person2 {
        p1,p2;
    }
    
  • package cn.itcast.reflect;
    
    
    public @interface Myanno {
        //注解可以返回的类型
        // 1.基本数据类   2.String   3.枚举  4.注解     5.以上类型的数组
        int show1();
        public abstract String show2() default "张三";
        public abstract Person2 per();
        Myanno2 anno2();
        //String[] strs();*/
    
    }
    
  • package cn.itcast.reflect;
    //String类型的返回值已经被default修饰了,可以不用对属性进行赋值
    @Myanno(show1=1,per=Person2.p1,anno2=@Myanno2)
    public class Worker {
    }
    
  • Notes 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 {
        //加法
        @Check
        public void add(){
            System.out.println("1+0="+(1+0));
        }
        //减法
        @Check
        public void sub(){
            System.out.println("1-0="+(1-0));
        }
        //乘法
        @Check
        public void mul(){
            System.out.println("1*0="+(1*0));
        }
        //除法
        @Check
        public void div(){
            System.out.println("1/0="+(1/0));
        }
        public void show(){
            System.out.println("永无bug");
        }
    }
    
  • package cn.itcast.reflect;
    
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.lang.reflect.Method;
    
    /**
     * 简单的测试框架
     * 当主方法执行后,会自动检测所有方法(加了Check注解的方法)
     */
    
    public class TestCheck {
        public static void main(String[] args) throws IOException {
            //创建计算器对象
            Calculator c = new Calculator();
            //获取字节码文件
           Class cls = c.getClass();
           //获取所有方法
            Method[] methods = cls.getMethods();
            int number =0;//出现异常的次数
            BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));
    
            for(Method method : methods){
                //判断方法上是否有Check注解
                if(method.isAnnotationPresent(Check.class)){
                    //有,执行
                    try{
                        method.invoke(c);
                    }catch (Exception e){
                        //捕获异常
                        //记录到文件中
                        number++;
                        bw.write("方法出异常了");
                        bw.newLine();
                        bw.write("异常名称:"+e.getCause());
                        bw.newLine();
                        bw.write("异常的原因"+e.getCause().getMessage());
                        bw.newLine();
                        bw.write("--------------------");
                        bw.newLine();
                    }
                    bw.write("本次测试一共出现"+number+"次异常");
                    bw.flush();
                }
            }
        }
    }
    
/*
*本次测试一共出现0次异常本次测试一共出现0次异常方法出异常了
异常名称:java.lang.ArithmeticException: / by zero
异常的原因/ by zero
--------------------
本次测试一共出现1次异常本次测试一共出现1次异常
/

Guess you like

Origin www.cnblogs.com/train99999/p/10953032.html