代码评审——对field.getType().getSimpleName()的判断问题

问题描述:

当项目中,需要根据类型来进行一些操作时,如果仅是简单用String.equals()来进行判断,很容易出现问题。

实例代码:

if ("Timestamp".equals(field.getType().getSimpleName())) {
//do something
}

此时,使用静态代码扫描工具,会出现以下提示:
Use an “instanceof” comparison instead.
在这里插入图片描述


原因分析:

静态工具代码扫描工具给出的解释为:

There is no requirement that class names be unique, only that they be unique within a package. Therefore trying to determine an object’s type based on its class name is an exercise fraught with danger. One of those dangers is that a malicious user will send objects of the same name as the trusted class and thereby gain trusted access.
Instead, the instanceof operator or the Class.isAssignableFrom() method should be used to check the object’s underlying type.

主要问题就是不能仅通过字符串名称来进行判断是否是同一个类,如果出现恶意的代码,就会引起bug。


解决方案:

只需要通过instanceof 或Class.isAssignableFrom()方法来进行判断即可。

if (field.getType().isAssignableFrom(java.sql.Timestamp.class)) {
//do something
}

项目实际意义:

在项目开发过程中,避免在判断类型时,仅唯一的通过字符串相等来进行判断,是不准确的。在实际运行过程中,会写的更加详细,以便保证代码的准确性。

boolean flag = false;
String simplelName = field.getType()getSimplellame();
if ("Timestamp".equals(simplelName)|| field.getType().isAssignableFrom(java.sql.Timestamp.class)){
	flag = true;
}
  • 14
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值