面对使用不熟悉的类时,应该如何入手与思考!

473 阅读2分钟

Offer 驾到,掘友接招!我正在参与2022春招系列活动-Debug实录任务,点击查看活动详情

问题描述

ReflectionTestUtils类 反射注入属性的一个方法setField

ReflectionTestUtils.setField(userController, "userService", userService);

       当我第一次见到ReflectionTestUtils,并且第一次在项目中使用反射将属性注入时。当时大脑是懵的,不知道如何下手。最开始我想着看组员是这么使用的这个工具类的,就如何照猫画虎的使用这个ReflectionTestUtils.setField的方法。但是当我发现项目中有很多的地方要使用此方法中,我觉得我这个照猫画虎的方法、思维是错误的!于是经过思考、反思与网上查阅资料,总结了下次面对新的一些工具类的使用时,应该如何思考与入手!

解题思路与步骤

解决思路:

当遇见不知道的类的方法使用时,可以通过ctrl + 鼠标左键跳转到方法的定义出,如何不能见名知意的话就下载download resource,里面有说明文档。如果还不能掌握用法,可以通过ctrl + h快捷键查看继承树,看别人怎么使用。当然,使用ctrl + B还可以查看此方法再什么位置被调用。

本问题解决步骤:

通过ctrl + 鼠标左键 定位到ReflectionTestUtils.setField处,如何发现不能通过名字就了解此方法这么使用,于是就下载download resource,最后通过看如下的解释,明白了ReflectionTestUtils.setField(Object targetObject, String name, @Nullable Object value)就是将value值注入targetObject的属性名为name的属性中。

本问题使用案例
//将userController中userService属性通过反射注入
ReflectionTestUtils.setField(userController, "userService", userService);
setFiled()文档源码:
/**
 * Set the {@linkplain Field field} with the given {@code name} on the
 * provided {@code targetObject} to the supplied {@code value}.
 * <p>This method delegates to {@link #setField(Object, String, Object, Class)},
 * supplying {@code null} for the {@code type} argument.
 * @param targetObject the target object on which to set the field; never {@code null}
 * @param name the name of the field to set; never {@code null}
 * @param value the value to set
 */
public static void setField(Object targetObject, String name, @Nullable Object value) {
   setField(targetObject, name, value, null);
}

总结反思

当遇见不熟悉的类的方法使用时,可以通过ctrl + 鼠标左键跳转到方法的定义出,如何不能见名知意的话就下载download resource,里面有说明文档。如果还不能掌握用法,可以通过ctrl + h快捷键查看继承树,看别人怎么使用。当然,使用ctrl + B还可以查看此方法再什么位置被调用。