博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
通过Java反射测试类私有成员
阅读量:6893 次
发布时间:2019-06-27

本文共 2267 字,大约阅读时间需要 7 分钟。

hot3.png

在Java开发阶段,因为追求架构规范和遵循设计原则,所以要用private和protected修饰符去定义类的成员方法、变量、常量,这使得代码具封装性、内聚性等,但在测试阶段会造成一定的不便。通过Java的反射机制,便能很好地解决该问题。

####ReflectUtil.java

<pre><code> //...... /** * @author yumin * @since 2015-03-02 14:52 */ public class ReflectUtil { private ReflectUtil() { } //部份代码略 public static Object invokeMethod(Object object, String methodName, Class[] parameterTypes, Object[] args) { Object result = null; if (null != object) { try { Method method = getDeclaredMethod(object, methodName, parameterTypes); result = method.invoke(object, args); } catch (NoSuchMethodException e) { //...... } catch (IllegalAccessException e) { //...... } catch (InvocationTargetException e) { //...... } } return result; } public static Method getDeclaredMethod(Object object, String methodName, Class[] parameterTypes) throws NoSuchMethodException { Method method = null; if (null != object) { method = object.getClass().getDeclaredMethod(methodName, parameterTypes); method.setAccessible(true); } return method; } } </code></pre>

####ReflectUtilTest.java

<pre><code> //...... /** * @author yumin * @since 2015-03-02 14:53 */ public class ReflectUtilTest { //部份代码略 @Test public void testInvokeMethod() throws Exception { String whatIsYourName = null; String howOldAreYou = null; String name = "yumin"; int age = 18; Person person = new Person(); whatIsYourName = (String) ReflectUtil.invokeMethod(person, "whatIsYourName", null, null); howOldAreYou = (String) ReflectUtil.invokeMethod(person, "howOldAreYou", new Class[]{int.class}, new Object[]{age}); Assert.assertEquals(Person.whatIsYourName + name, whatIsYourName); Assert.assertEquals(Person.howOldAreYou + age, howOldAreYou); } public class Person { public static final String whatIsYourName = "My name is "; public static final String howOldAreYou = "I'm "; private String name = "yumin"; // 姓名 public void setName(String name) { this.name = name; } private String whatIsYourName() { return whatIsYourName + name; } private String howOldAreYou(int age) { return howOldAreYou + age; } } } </code></pre>

可以看到通过Java反射机制,实现了对被private和protected所修饰方法和属性的调用、取值、传值等读写操作,未破坏原始代码也能完成对私有成员的单元测试。需要特别注意的是,建议仅运用在测试场景,切莫图方便在生产环境发行的代码逻辑中也通过反射调用类私有成员,这样便破坏原有的类设计,产生不可预料的结果及污染体系结构造成后续难以维护。

更详细代码请参见:

转载于:https://my.oschina.net/wangyumin/blog/387627

你可能感兴趣的文章
DOM设置表格隔行变色js代码及鼠标悬停在哪行,哪行字体就加粗效果
查看>>
GII 和 DEBUG 模块出现 403 解决
查看>>
shell历史命令记录功能
查看>>
kali linux软件源
查看>>
centos6设置静态IP
查看>>
cocos2d_x在windows环境下的方向键支持
查看>>
Mysql数据库恢复,Ibdata1文件删除数据恢复成功
查看>>
Maven学习总结(11)——Maven Tomcat7自动部署
查看>>
Shell 中常用的sqlplus 代码段
查看>>
Maven学习总结(1)——Maven入门
查看>>
Linux java环境配置
查看>>
mysql ====查询命令介绍(5)
查看>>
Ffmpeg,mencoder视频格式转换
查看>>
【经验收集】完全卸载SQLServer 2008 R2的步骤
查看>>
Spring Boot 项目启动顺序以及常见注解作用
查看>>
java基础(2)
查看>>
zabbix安装界面报连接不到数据
查看>>
一首Python的打油诗
查看>>
pjsip 同时使用多套音频设备
查看>>
DevOps:怎么实现源代码注释和系统文档的自动化更新?
查看>>