Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic Observer Pattern implementation unchecked call as raw type

Tags:

java

unchecked

I am currently trying to utilize a generic implementation of the Observer Pattern in Java I found that seems to work quite well except for the fact that it generates unchecked call warnings that I'd like to fix if possible. The implementation looks like this:

The interface, IObservable.java:

public interface IObservable<T> {
    void addObserver(IObserver<T> observer);
    void removeObserver(IObserver<T> observer);
}

The base class Observable.java:

import java.util.ArrayList;

public class Observable<T> implements IObservable<T> {
    private final ArrayList<IObserver<T>> observers
            = new ArrayList<IObserver<T>>();

    public void addObserver(IObserver<T> observer) {
        synchronized (observers) {
            observers.add(observer);
        }
    }

    public void removeObserver(IObserver<T> observer) {
        synchronized (observers) {
            observers.remove(observer);
        }
    }

    protected void notifyObservers(final T t) {
        synchronized (observers) {
            for (IObserver<T> observer : observers) {
                observer.notify(t);
            }
        }
    }
}

The observer interface IObserver.java:

public interface IObserver<T> {
    void notify(T model);
}

My Observable class Subject.java:

public class Subject extends Observable {
    private int foo;
    private int bar;

    public int getFoo() { return foo; }
    public int getBar() { return bar; }

    public void setFoo(int f) {
        foo = f;
        notifyObservers(this);
    }

    public void setBar(int b) {
        bar = b;
        notifyObservers(this);
    }
}

The unchecked call warnings occur on each call to notifyObservers. The full warning is

java: warning: [unchecked] unchecked call to notifyObservers(T) as a member of the raw type com.foo.Observable

Is there any way to fix this, or should I just use @suppressWarnings("unchecked")? Or perhaps I should as is this even, in fact, a safe method call?

like image 575
qwertymodo Avatar asked Feb 11 '14 21:02

qwertymodo


2 Answers

You didn't provide a type parameter for Observable in your extends clause for Subject. Since you declared Observable<T> in that class, you should declare:

public class Subject extends Observable<Subject> {
  ...
}
like image 163
Thorn G Avatar answered Oct 01 '22 11:10

Thorn G


Your Subject class implements the raw form of the Observable class. You should do one of the following:

1) Extend the generic form of Observable by supplying a reference type as the generic type parameter, e.g.

public class Subject extends Observable<Foo>

OR

2) Make your Subject class generic too.

public class Subject<T> extends Observable<T>
like image 43
rgettman Avatar answered Oct 01 '22 12:10

rgettman