简体   繁体   English

检查java列表 <object> 对象类型

[英]Checking java List<object> object type

I have a generic function that returns a List<?> . 我有一个返回List<?>的泛型函数。 If it works correctly, it will return a List<LightSensor> , but I cannot directly convert the result of the function to a variable of type List<LightSensor> . 如果工作正常,它将返回List<LightSensor> ,但是我无法直接将函数的结果转换为List<LightSensor>类型的变量。 How can I check if the class in the List is a LightSensor correctly? 如何检查列表中的类是否正确是LightSensor? (eg check if List<?> = List<LightSensor> ) Also, What is the best way to cast it correctly once I've checked? (例如,检查List<?> = List<LightSensor> )另外,检查后正确投射的最佳方法是什么?
BTW the class LightSensor extends Object and a version of Serializable 顺便说一句,LightSensor类扩展了Object和一个Serializable版本

How can I check if the class in the List is a LightSensor correctly? 如何检查列表中的类是否正确是LightSensor? (eg check if List<?> = List<LightSensor> ) (例如,检查List<?> = List<LightSensor>

AFAIK, the only way to do this is to iterate the list and use instanceof LightSensor or getClass() == LightSensor.class on each element. AFAIK,执行此操作的唯一方法是对列表进行迭代,并在每个元素上使用instanceof LightSensorgetClass() == LightSensor.class

Also, What is the best way to cast it correctly once I've checked? 另外,检查后正确投射的最佳方法是什么?

Just do a typecast, and suppress the "unchecked conversion" warning. 只是进行类型转换,并取消显示“未经检查的转换”警告。

Well the idiom to return a generic collection from a method is something like: 好吧,从方法返回通用集合的习惯是这样的:

public <T> List<T> getTheList(Class<T> cls){
  // you might need the cls in here to create the list.
  ...
}

Obviously the way you use the Class<T> to generate the list is application specific. 显然,使用Class<T>生成列表的方式是特定于应用程序的。 Most of the times this makes sense in the context of some class hierarchy, in which case T extends some base class or interface: 在大多数情况下,这在某些类层次结构的上下文中是有意义的,在这种情况下, T扩展了一些基类或接口:

public <T extends MyBaseClassOrInterface> List<T> getTheList(Class<T> cls){
  ...
}

Again, the way you create the list is completely application dependent. 同样,创建列表的方式完全取决于应用程序。 If you try to keep your whole application strongly typed you might be able to avoid doing some kind of black magic to figure out the type parameter of List<?> . 如果您尝试使整个应用程序保持强类型,则可以避免执行某种黑魔法来找出List<?>的类型参数。 It's a strong code smell if you end up with code like that (unless obviously you are dealing with some legacy code). 如果最终得到这样的代码,这会产生强烈的代码味道(除非显然您正在处理一些旧代码)。 Besides, if the list is empty you are absolutely hopeless. 此外,如果列表为空,则绝对是绝望的。

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

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