Question

I have an Observer that is expecting two possible objects from an observable: List<Cat> or List<Orange>, mutually exclusive. How might I distinguish which data type was passed to update(Observable observable, Object data)? I cannot use if(data instanceof List<Cat>) because of type erasure at runtime?

Was it helpful?

Solution

Get the first element in your List (assuming is not empty) and test the type of the element retrieved. You may use instanceof operator to see if the object is in the class hierarchy of the desired class, but if you want a more accurate test, use getClass().equals(YourClass.class).

public void foo(List<Object> list) {
    if (!list.isEmpty()) {
        Object object = list.get(0);
        //using instanceof
        if (object instanceof Cat) {
        }
        if (object instanceof Orange) {
        }
        //using getClass().equals
        if (object.getClass().equals(Cat.class)) {
        }
        if (object.getClass().equals(Orange.class)) {
        }
    }
}

OTHER TIPS

i know this is not what really PO want but i think this may helpful. Wrapers can help in this situation. you can create two Class and one interface:

interface SpecialList<T> {
  T get(int i);
  void add(T item);
}


class CatList implements SpecialList<Cat> {
  private List<Cat> list;
...
}

class OrangeList implements SpecialList<Orange> {
  private List<Cat> list;
...
}

then Observable can return a SpecialList object. in this case instance of will work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top