java.lang.reflect.Field getType()结果无法与使用equals()的类型进行比较

时间:2016-08-23 06:58:06

标签: java reflection

我最有可能在这个简单的用例中监督一些事情。 我的代码遍历类中的带注释的字段,而对于每个字段,我想根据类型运行一些代码。最简单的只是设置一个值:

field.setAccessible(true);
final Class<?> type = field.getType();
if (type.equals(Boolean.class)) {
    field.set(this, Boolean.parseBoolean(property));
} else if (type.equals(Integer.class)) {
    field.set(this, Integer.parseInt(property));
} else if (type.equals(String.class)) {
    field.set(this, property);
} else {
    LOGGER.warn("Cannot parse property -{}{}. Unknown type defined.", option.getOpt(),
            field.getName());
}

但是这个检查:

if (type.equals(Boolean.class))

不按预期工作,例如对于定义为private boolean isVerbose;的字段。在检查type后,我将name属性视为仅"boolean" Boolean.class属性name填充了"java.lang.Boolean"。这些对象不同。

这种情况的正确实施是什么?

3 个答案:

答案 0 :(得分:0)

在Java中,booleanBoolean有两种不同的类型:boolean是原始数据类型,而Booleanjava.lang.Boolean中的类。在此示例中,您在班级中使用的private boolean isVerbose不是java.lang.Boolean类型。因此,您必须将其更改为private Boolean isVerbose。 希望这有助于!!!!!!

答案 1 :(得分:0)

看一下这篇文章:Check type of primitive field

基本上你需要分别检查原始类型(Boolean.TYPELong.TYPE等)

if (field.getType().equals(Boolean.TYPE) {
  // do something if field is boolean
}

答案 2 :(得分:0)

我相信你遇到了java原语和拳击的麻烦。 java.lang.Boolean是一个类,其中&#34; boolean&#34;只表示原始类型。

你宣布这是一个区别:

private boolean myBool; // this a java primitive
private Boolean myOtherBool; // this is an object

Java会根据需要自动在这些类型之间进行转换,但是当您自己检查类型时,您必须注意这一点。

同样如此: - 整数 - 长 - 短 - 字节

我希望我没有忘记任何事情。

相关问题