我怎样才能让这种东西起作用?我可以检查是否(obj instanceof List<?>)
但不是(obj instanceof List<MyType>)
。有没有办法可以做到这一点?
这是不可能的,因为在泛型编译时数据类型擦除。只有这样做的可能方法是编写某种包含列表所包含类型的包装器:
public class GenericList <T> extends ArrayList<T>
{
private Class<T> genericType;
public GenericList(Class<T> c)
{
this.genericType = c;
}
public Class<T> getGenericType()
{
return genericType;
}
}
if(!myList.isEmpty() && myList.get(0) instanceof MyType){
// MyType object
}
您可能需要使用反射来获取要检查的类型。获取List的类型:Get generic type of java.util.List
如果你想检查object
是非空的List<T>
的实例,可以使用这个:
if(object instanceof List){
if(((List)object).size()>0 && (((List)object).get(0) instanceof MyObject)){
// The object is of List<MyObject> and is not empty. Do something with it.
}
}
如果要验证Object的List或Map值的引用是否是Collection的实例,只需创建所需List的实例并获取其类...
Set<Object> setOfIntegers = new HashSet(Arrays.asList(2, 4, 5));
assetThat(setOfIntegers).instanceOf(new ArrayList<Integer>().getClass());
Set<Object> setOfStrings = new HashSet(Arrays.asList("my", "name", "is"));
assetThat(setOfStrings).instanceOf(new ArrayList<String>().getClass());
如果这不能用泛型包装(@Martijn的答案),最好不要强制传递它以避免冗余列表迭代(检查第一个元素的类型保证什么都没有)。我们可以在迭代列表的代码段中转换每个元素。
Object attVal = jsonMap.get("attName");
List<Object> ls = new ArrayList<>();
if (attVal instanceof List) {
ls.addAll((List) attVal);
} else {
ls.add(attVal);
}
// far, far away ;)
for (Object item : ls) {
if (item instanceof String) {
System.out.println(item);
} else {
throw new RuntimeException("Wrong class ("+item .getClass()+") of "+item );
}
}
您可以使用假工厂包含许多方法,而不是使用instanceof:
public class Message1 implements YourInterface {
List<YourObject1> list;
Message1(List<YourObject1> l) {
list = l;
}
}
public class Message2 implements YourInterface {
List<YourObject2> list;
Message2(List<YourObject2> l) {
list = l;
}
}
public class FactoryMessage {
public static List<YourInterface> getMessage(List<YourObject1> list) {
return (List<YourInterface>) new Message1(list);
}
public static List<YourInterface> getMessage(List<YourObject2> list) {
return (List<YourInterface>) new Message2(list);
}
}