将未知对象转换为布尔

时间:2017-03-08 00:24:36

标签: java casting

我有一个Map <String,Object>的数组映射。 Object将是一种简单类型(StringIntegerBoolean,...)。

我正在尝试做类似

的事情
Boolean isSet = (Boolean) metaMap.get("is_set");
if (isSet) ...

metaMap.get("is_set")可能未设置,因此可以返回null;或已设置,但可能正在使用0/1 true/false"true"/"false"

如何将所有这些情况转换为布尔值?

我意识到使用if/else的{​​{1}}解决方案。我想知道是否有更简单的解决方案。

2 个答案:

答案 0 :(得分:0)

由于您提供的信息很少,我将假设您完全控制代码 - 特别是数组的创建。

不是在数组中使用Map<String, T>,而是使用与下面类似的方法创建和使用接口,并从中派生类StringMetaMapIntegerMetaMap等。

public interface MetaMap
{
 // returns true, if property is contained
 public boolean hasProperty(String property);

 // returns non-null value of property or throws an exception
 public boolean getPropertyOrThrow(String property) throws IllegalArgumentException;

 // returns null or property value (use methods above if you want to avoid null values)
 public Boolean getProperty(String property);
}

这些类封装了它们如何编码布尔值,并允许通过接口轻松处理。

答案 1 :(得分:-3)

为什么不直接使用map.entrySet()。Stream.filter(e - &gt; e!= null).collect()来创建一个过滤掉空值的地图。