获取列表类型<MyModelClass>

Get type of List<MyModelClass>

我在 recycylerView 中膨胀多个布局视图并通过重写 getItemViewType() 方法获得 viewType

@Override
    public int getItemViewType(int position) {

        Log.e("getItemViewType ", myAllItemsList.get(position).getClass()+"");
        if (myAllItemsList.get(position) instanceof MyCategory) {
            return CATEGORY_VIEW;
        } else if (myAllItemsList.get(position) instanceof MyPromotion) {
            return PROMOTION_VIEW;
        } else {
            return ITEM_VIEW;
        }
    }

因为 myAllItemsList 是对象类型

private List<Object> myAllItemsList = new ArrayList<>();

我正在向它传递三种类型的对象

  1. List<MyCategory>
  2. MyPromotion
  3. List<MyItem>

在调用上述方法时,if condition 永远不会执行,因为 myAllItemsList 中没有类似 MyCategory 的内容,而是包含 List<MyCategoty>。当我尝试

myAllItemsList.get(position) instanceof List<MyCategory>

Android 工作室说 Illegal generic type for instenceof

所以我的问题是我怎样才能知道 myAllItemsList 包含 List<MyCategory> 以便我 return CATEGORY_VIEW。 任何帮助将不胜感激。

我通过获取对象解决了这个问题,并第一次检查它是否属于 List 类型,然后迭代此列表的元素并检查它是否为 instenceof MyClass (MyCategory)。

Object o = myAllItemsList.get(position);
        if (o instanceof List) {
            for (Object obj : (List) o) {
                if (obj instanceof MyCategory) {
                    Log.e("InsideInstenceof", "Success");
                    return CATEGORY_VIEW;
                }
            }
            return ITEM_VIEW;
        } else if (o instanceof MyPromotion) {
            return PROMOTION_VIEW;
        }