Junit,反射,注解
Junit单元测试
测试分类:
黑盒测试:不需要写代码,给输入值,看程序是否能够输出期望值
白盒测试:需要写代码,关注程序具体的执行流程
Junit使用:白盒测试
步骤
定义一个测试类(测试用例)
建议:
测试类名:被测试的类名Test
包名:xxx.xxx.xxt.est
定义测试方法:可以独立运行
建议:
方法名:test测试的方法名
返回值:void
参数列表:空参
给方法加@Test
导入junit依赖环境
判断结果
红色:失败
绿色:成功
一般我们会使用断言操作来处理结果
Assert.assertEquals(期望结果,运算结果)
补充
@Before:
修饰的方法会在测试方法之前被自动执行
@After:
修饰的方法会在测试方法之后被自动执行
package com.jx.day01_basic.test;
import com.jx.day01_basic.junit.Calculator;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CalculatorTest {
/**
* 初始化方法
* 用于资源申请,所有测试方法在执行之前都会先执行改方法
*/
@Before
public void init(){
System.out.println("init......");
}
/**
* 释放资源方法
* 在所有测试方法执行后,自动执行该方法
*/
@After
public void close(){
System.out.println("close....");
}
@Test
public void testAdd(){
//1.创建计算器对象
Calculator c=new Calculator();
//2.调用add方法
int result=c.add(1,2);
System.out.println("testAdd...");
// System.out.println(result);
//3.断言 我断言这个结果是3
Assert.assertEquals(3,result);
}
@Test
public void testSub(){
Calculator c=new Calculator();
int result=c.sub(1,2);
System.out.println("testSub...");
Assert.assertEquals(-1,result);
}
}
反射
框架设计的灵魂
框架:半成品软件。可以在框架的基础上进行软件开发,简化编码
反射:将类的各个组成部分封装为其他对象,这就是反射机制
好处:
可以在程序运行过程中,操作这些对象
可以解耦,提高程序的可扩展性
获取class对象的方式
Class.forName("全类名"):将字节码文件加载进内存,返回Class对象
多用于配置文件,将类名定义的配置文件中,读取文件,加载类
类名.class:通过类名的属性class获取
多用于参数的传递
对象.getClass():getClass()方法在Object类中定义着
多用于对象的获取字节码方式
总结
同一个字节码文件(*.class)在一次程序运行过程中,只会被加载一次,不论通过哪一种方式获取Class对象都是同一个
Class对象功能
获取成员变量们
Filed[] getFileds() 获取所有public修饰的成员变量
Filed[] getFileds(String name) 获取指定public修饰的成员变量
Filed[] declareFields() 获取所有成员变量不考虑修饰符
获取构造方法们
获取成员方法们
获取类名
Filed:成员变量
操作
设置值
void set(Object obj,Object value)
获取值
get(Object obj)
忽略访问权限修饰符的安全检查
setAccessible(true) 暴力反射
public class ReflectDemo02 {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
//0.获取Person的Class对象
Class personClass= Person.class;
//1.Field[] fileds 获取所有public修饰的成员变量
Field[] fileds=personClass.getFields();
for (Field filed : fileds) {
System.out.println(filed);
}
System.out.println("=========");
//2.Filed getField(String name) 获取指定public修饰的成员变量
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("=====");
//Field[] declareFields 获取所有成员变量不考虑修饰符
Field[] declareFields=personClass.getDeclaredFields();
for (Field declareField : declareFields) {
System.out.println(declareField);
}
//Field getDeclaredField(String name)
Field d=personClass.getDeclaredField("d");
//忽略访问权限修饰符的安全检查
d.setAccessible(true);//暴力反射
Object vaule2=d.get(p);
System.out.println(vaule2);
}
}
Constructor:构造方法
创建对象
T newInstance(Object...initargs)
如果使用空参数构造方法创建对象,操作可以简化:class对象的newInstance方法
public class ReflectDemo03 {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//0.获取Person的Class对象
Class personClass= Person.class;
//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);
Constructor constructor1=personClass.getConstructor();
System.out.println(constructor1);
//创建对象
Object person1=constructor1.newInstance();
System.out.println(person1);
Object o=personClass.newInstance();
System.out.println(o);
constructor1.setAccessible(true);
}
}
Method:方法对象
执行方法:
Object invoke(Object obj,object...args)
获取方法名称:
String getName:获取方法名
public class ReflectDemo04 {
public static void main(String[] args) throws Exception {
//0.获取Person的Class对象
Class personClass= Person.class;
//获取指定名称的方法
Method eat_method=personClass.getMethod("eat",String.class);
Person p=new Person();
//执行方法
eat_method.invoke(p,"vegetables");
System.out.println("........");
//获取所有public修饰的方法
Method[] methods=personClass.getMethods();
for (Method method : methods) {
System.out.println(method);
String name=method.getName();
System.out.println(name);
}
//获取类名
String className=personClass.getName();
System.out.println(className);
}
}
案例:
需求:写一个”框架“,可以帮我们创建任意类的对象,并且执行其中任意方法
实现:
配置文件
反射
步骤:
将需要创建的对象的全类名和需要执行的方法定义在配置文件中
在程序中加载读取配置文件
使用反射技术来加载类文件进内存
创建对象
执行方法
className=com.jx.day01_basic.domain.Person
methodName=eat
package com.jx.day01_basic.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 {
//可以创建任意类的对象,可以执行任意方法
// Person p=new Person();
// p.eat("qq");
// Student student=new Student();
// student.sleep();
//1.加载配置文件
//1.1创建Properties对象
Properties pro=new Properties();
//1.2加载配置文件,转换为一个集合
//1.2.1获取class目录下的配置文件
ClassLoader classLoader=ReflectTest.class.getClassLoader();
InputStream is=classLoader.getResourceAsStream("pro.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);
//执行方法
method.invoke(obj);
}
}
注解
作用分类:
编写文档:通过代码里标识的注解生成文档【生成doc文档】
代码分析:通过代码里标识的注解对代码进行分析【使用反射】
编译检查:通过代码里标识的注解让编译器能够实现基本的编译检查【override】
JDK中预定义的一些注解
自定义注解
在程序使用(解析)注解
@Override:检测被该注解标注的方法是否是继承自父类(接口)的
@Deprecated:该注解标注的内容,表示已过时
@SuppressWarnings:压制警告
一般传递参数all @SuppressWarnings("all")
自定义注解
格式:
元注解
public @interface 注解名称 {
}
本质
注解本质是一个接口,该接口默认继承Annotion接口
public interface MyAnno extends java.lang.annotation.Annotation {
}
属性
接口中可以定义的成员方法
要求:
属性的返回值类型
基本数据类型
String
枚举
注解
以上类型的数组
定义了属性,在使用时需要给属性赋值
如果定义属性时,使用default关键字给属性默认初始值,则使用注解时,可以不进行属性赋值
如果只有一个属性需要赋值,并且属性的名称是value,则value可以省略,直接定义值
给数组赋值时,使用{}包裹,如果数组中只有一个值,则{}省略
元注解
用于描述注解的注解
@Target:描述注解能够作用的位置
ElementType取值:
TYPE:作用于类上
METHOD:作用于方法上
FIELD:作用于成员变量上
@Retention:描述注解被保留的阶段
@Retention(RetentionPolicy.RUNTIME):当前被描述的注解,会保留到class字节码文件中,被JVM读取到
@Documented:描述注解是否被抽取到api文档中
@Interited:描述注解是否被子类继承
@Target(value = {ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnno3 {
}
在程序使用注解
获取注解中定义的属性值
获取注解定义的位置对象(Class,Method,Filed)
获取指定的注解
public class ProImpl implements Pro{
public String className(){
return "com.jx.day01_basic.annotation.Demo01";
}
public String methodName(){
return "show";
}
}
调用注解中的抽象方法获取配置的属性值
package com.jx.day01_basic.annotation;
import java.lang.reflect.Method;
@Pro(className = "com.jx.day01_basic.annotation.Demo01",methodName = "show")
public class ReflectTest {
public static void main(String[] args) throws Exception {
//1.解析注解
//1.1获取该类的字节码文件对象
Class<ReflectTest> reflectTestClass=ReflectTest.class;
//2.获取上边的注解对象
//其实就是在内存中生成了一个该注解接口的子类实现对象
Pro an=reflectTestClass.getAnnotation(Pro.class);
//3.调用注解对象中定义的抽象方法,获取返回值
String className=an.className();
String methodName=an.methodName();
System.out.println(className);
System.out.println(methodName);
//加载类
Class cls=Class.forName(className);
//创建对象
Object obj=cls.newInstance();
//获取方法对象
Method method=cls.getMethod(methodName);
//执行方法
method.invoke(obj);
}
}
案列
package com.jx.day01_basic.annotation.demo;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.management.BufferPoolMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestCheck {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, IOException {
//1.创建计算器对象
Calculator c=new Calculator();
//2.获取字节码文件对象
Class cls=c.getClass();
//3.获取所有方法
Method[] methods=cls.getMethods();
int num=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){
e.printStackTrace();
num++;
bw.write(method+"方法出错了");
bw.newLine();
bw.write("异常名称"+e.getCause().getClass().getSimpleName());
bw.newLine();
bw.write("异常原因"+e.getCause().getMessage());
bw.newLine();
bw.write(".......");
}
}
}
bw.write("本次测试一共出现"+num+"次异常");
bw.flush();
bw.close();
}
}
className=com.jx.day01_basic.domain.Person
methodName=eat