简体   繁体   English

无法将BasicDBList转换为数组(java)

[英]Cannot convert BasicDBList to array (java)

I have a MongoDB collection where documents contain several arrays. 我有一个MongoDB集合,其中文档包含多个数组。 I"m retrieving those documents and storing their data into POJOs. 我正在检索这些文档并将其数据存储到POJO中。

In some instances, I can do this: 在某些情况下,我可以这样做:

BasicDBList kws = (BasicDBList)obj.get(Constants.KEYWORDS_STR);
if(!kws.isEmpty())  
    tb.setKeywords(kws.toArray(new String[0]));

However, I have one array that's stumping me. 但是,我有一个困扰我的数组。 I thought it contained Longs, but toArray(new Long[0]) throws java.lang.ArrayStoreException. 我以为它包含Longs,但是toArray(new Long [0])抛出java.lang.ArrayStoreException。 I figured ok, for some reason they are stored as Strings, and tried converting to an array of Strings, and still got a java.lang.ArrayStoreException. 我想好了,出于某种原因它们被存储为Strings,并尝试转换为Strings数组,但仍然得到java.lang.ArrayStoreException。

How can I tell what class the BasicDBList thinks it has stored in it? 我怎么知道BasicDBList认为它存储在哪个类中?

通过获取BasicDBList的迭代器并查看对象,我发现它持有Integers(这很奇怪,因为它应该是Longs,但这是另一个问题的主题)。

Since BasicDBList extends ArrayList<Object> , (note - generics are not used), so there's no guarantee that kws will contain homogeneous types within it. 由于BasicDBList extends ArrayList<Object> ,(请注意-不使用泛型),因此不能保证kws会在其中包含同质类型。 You should be able to change new String[0] to new Object[0] and avoid the exception. 您应该能够将new String[0]更改为new Object[0]并避免出现异常。

There's no way to easily interrogate the array without some kind of statements: 没有某种语句就无法轻松查询数组:

if (instanceof ){...} 
else if (instanceof) {...}

Your data model should be mapped out well enough that this pattern is not required, or at least well enough that you know the finite set of what to expect. 您的数据模型应该映射得足够好,以至于不需要这种模式,或者至少映射得足够好,以至于您知道期望的有限集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM