Day01--Junit、反射和注解

2019-08-05  本文已影响0人  pure_joy

一、Junit单元测试

package com.djx.test;

import com.djx.junit.Calculator;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class CalcuatorTest {
    /**
     * 初始化方法:
     * 用于资源申请,所有测试方法在执行之前都会先执行该方法
     */
    @Before
    public void init(){
        System.out.println("init...");
    }

    /**
     * 释放资源方法:
     * 在所有测试方法执行完后,都会自动执行该方法
     */
    @After
    public void close(){
        System.out.println("close...");
    }

    /**
     * 测试add方法
     */
    @Test
    public void testAdd(){
        System.out.println("testAdd...");
        //1、创建对象
        Calculator c = new Calculator();
        //2、调用
       int result =  c.add(0,2);
        //System.out.println(result);

        //3、断言 我断言这个结果是3
        Assert.assertEquals(3,result);
    }
}

二、反射:框架设计的灵魂

public class ReflectDemo1 {

    /**
     * 获取Class对象的方式
     */
    public static void main(String[] args) throws Exception {

        //1、Class.forName("全类名")
        Class cls1 = Class.forName("com.djx.domain.Person");
        System.out.println(cls1);
        //2、类名.class
        Class cls2 = Person.class;
        System.out.println(cls2);
        //3、对象.getClass()
        Person p = new Person();
        Class cls3 = p.getClass();
        System.out.println(cls3);

        //== 比较三个对象
        System.out.println(cls1 == cls2);//true
        System.out.println(cls1 == cls3);//true
    }
}
package com.djx.reflect;

import com.djx.domain.Person;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectDemo {
    public static void main(String[] args) throws Exception {
        //0、获取Person的Class对象
        Class personClass = Person.class;
        //1、Field[] getFileds():获取所有public修饰的成员变量们
        Field[] fields = personClass.getFields();
        for (Field field : fields)
        {
            System.out.println(field);
        }

        System.out.println("----------------------------");
        //2、Field getField(String name)
        Field a = personClass.getField("a");
        //获取成员变量a的值
        Person p = new Person();
        Object value = a.get(p);
        System.out.println(value);
        //设置a的值
        a.set(p,"张三");
        System.out.println(p);

        System.out.println("================");

        //Filed[] getDeclaredFields():获取所有的成员变量,不考虑修饰符
        Field[] declaredFileds = personClass.getDeclaredFields();
        for (Field declaredField : declaredFileds){
            System.out.println(declaredField);
        }
        //Field getDeclaredField(String name)
        Field d = personClass.getDeclaredField("age");
        //忽略访问权限修饰符的安全检查
        d.setAccessible(true);//暴力反射
        Object value2 = d.get(p);
        System.out.println(value2);

        //Constructor<T> getConstructor(类<?>... parameterTypes)
        Constructor constructor = personClass.getConstructor(String.class, int.class);
        System.out.println(constructor);
        //创建对象
        Object person = constructor.newInstance("张三", 23);
        System.out.println(person);

        Object o = personClass.newInstance();
        System.out.println(o);

        //获取指定名称的方法
        Method eat_method = personClass.getMethod("eat");
        //执行方法
        eat_method.invoke(p);
    }
}
案例:
/**
 * 需求:写一个“框架”,不能改变该类的任何代码的前提下,可以帮我们创建任意类的对象,并执行其中任意方法。
 *      * 实现:
 *          1、配置文件
 *          2、反射
 *      * 步骤:
 *          1、将需要创建的对象的全类名和需要执行的方法定义在配置文件中
 *          2、在程序中加载读取配置文件
 *          3、使用反射技术来加载类文件进内存
 *          4、创建对象
 *          5、执行方法
 *框架类
 */
public class ReflectTest {
    public static void main(String[] args) throws Exception {
        //可以创建任意类的对象,可以执行任意方法

        /*
            前提:不能改变该类的任何代码。可以创建任意类的对象,可以执行任意方法
         */
        /*Person p = new Person();
        p.eat();*/

        //1、加载配置文件
        //1.1、创建Properties对象
        Properties pro = new Properties();
        //1.2、加载配置文件,转换为一个集合
        //1.2.1、获取class目录下的配置文件
        ClassLoader classLoader = ReflectTest.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("prop.properties");
        pro.load(is);

        //2、获取配置文件中定义的数据
        String className = pro.getProperty("className");
        String methodName = pro.getProperty("methodName");

        //3、加载该类进内存
        Class cls = Class.forName(className);
        //4、创建对象
        Object obj = cls.newInstance();
        //5、获取方法对象
        Method method = cls.getMethod(methodName);
        //6、执行方法
        method.invoke(obj);
    }
}
prop.properties
className=com.djx.domain.Student
methodName=sleep

三、注解

package com.djx.annotation;

import java.lang.reflect.Method;

@Pro(className = "com.djx.annotation.Demo1",methodName = "show")
public class ReflectTest {
    public static void main(String[] args) throws  Exception{
        /*
            前提:不能改变该类的任何代码。可以创建任意类的对象,可以执行任意方法
         */

        //1、解析注解
        //1.1、获取该类的字节码文件对象
        Class<ReflectTest> reflectTestClass = ReflectTest.class;
        //2、获取上边的注解对象
        //其实就是在内存中生成了一个该注解接口的子类实现对象
        /*
            public class ProImpl implements Pro{
                public String className(){
                    return "com.djx.annotation.Demo1";
                }

                public String methodName(){
                    return "show";
                }
            }
         */
        Pro an = reflectTestClass.getAnnotation(Pro.class);
        //3、调用注解对象中定义的抽象方法,获取返回值
        String className = an.className();
        String methodName = an.methodName();
        //4、加载该类进内存
        Class cls = Class.forName(className);
        //5、创建对象
        Object obj = cls.newInstance();
        //6、获取方法对象
        Method method = cls.getMethod(methodName);
        //7、执行方法
        method.invoke(obj);
    }
}
Pro.java
package com.djx.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 描述需要执行的类名和方法名
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Pro {

    String className();
    String methodName();
}
案例
package com.djx.annotation.Demo;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 简单的测试框架
 *
 * 当主方法执行后,会自动自行被检测的所有方法(加了Check注解的方法),判断方法是否有异常,记录到文件中
 */
public class TestCheck {

    public static void main(String[] args) throws IOException {
        //1、创建计算器对象
        Calculator c = new Calculator();
        //2、获取字节码文件对象
        Class cls = c.getClass();
        //3、获取所有方法
        Method[] methods = cls.getMethods();

        int number = 0;//出现异常的次数
        BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));

        for (Method method : methods) {
            //4、判断方法上是否有Check注解
            if(method.isAnnotationPresent(Check.class)){
                //5、有 执行
                try {
                    method.invoke(c);
                } catch (Exception e) {
                    //6、捕获异常

                    //记录到文件中
                    number++;

                    bw.write(method.getName()+" 方法出异常了");
                    bw.newLine();
                    bw.write("异常的名称:"+e.getCause().getClass().getSimpleName());
                    bw.newLine();
                    bw.write("异常的原因:"+e.getCause().getMessage());
                    bw.newLine();
                    bw.write("-----------------------------------");
                    bw.newLine();
                }
            }
        }
        bw.write("本次测试一共出现"+number+"次异常。");

        bw.flush();
        bw.close();
    }
}
Check.java
package com.djx.annotation.Demo;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {
}
上一篇 下一篇

猜你喜欢

热点阅读