我有一个 Map <String,Object>
的数组映射. Object
将是一个简单类型( String
、 Integer
、 Boolean
、...)。
我正在尝试做类似的事情
Boolean isSet = (Boolean) metaMap.get("is_set");
if (isSet) ...
metaMap.get("is_set")
可能未设置,因此它可以返回 null;或者已设置但可能正在使用 0/1
true/false
或 "true"/"false"
.
如何将所有这些情况转换为 boolean 值?
我意识到有 if/else
使用解决方案instanceof
.我想知道是否有更简单的解决方案。
最佳答案
由于您提供的信息很少,我假设您可以完全控制代码 - 特别是数组的创建。
而不是使用 Map<String, T>
在数组中,使用类似于下面的方法创建和使用接口(interface),并派生类 StringMetaMap
, IntegerMetaMap
等等。
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);
}
这些类封装了它们如何编码 boolean 值并允许通过接口(interface)轻松处理。
关于java - 将未知对象转换为 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42660813/