Search code examples
observer-patternobservers

Observable - Observer (java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to..)


The issue I face is how to segregate the Object data coming from the 3rd Party API notifyObservers of Observable.

The program is based on Observer pattern & I am able to successfully link the Observer to the 3rd party API Observable, which is triggering the Update method in the Observer.

Code: notifyObservers of Observable:

public void newData(String car,String model,CustFeedBack csFeed){
     setChanged();
     notifyObservers(new Object[]{car,model,csFeed});
 }

In the Observer Update method am trying to cast arg so that I can get each of the 3 data in the Object coming from the nofifyObservers

@Override
public void update(Observable observable, Object arg) {
        dataSubject = (DataSubject) arg;
        System.out.println(dataSubject.length);
        display();
 }

I am getting a java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to... Hope the issue I face is clear & await guidance on how I can proceed to break down the object data into 3 separate parts.


Solution

  • Here's my comment as an answer :)

    update is being called by your notifyObservers method, I guess? You're passing an array of objects to those update methods and are trying to cast this array into a type. I think you should cast it into an array of objects, instead. Should be something like Object[] values = (Object[])arg