I'm currently trying to use a generic implementation of the Observer pattern in Java, which seems to work quite well, except for the fact that it generates unverified call alerts that I would like to fix if possible. The implementation is as follows:
Interface, IObservable.java:
public interface IObservable<T> {
void addObserver(IObserver<T> observer);
void removeObserver(IObserver<T> observer);
}
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);
}
}
}
}
IObserver.java observer interface:
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);
}
}
Unverified call alerts occur on every call to notifyObservers. Full warning
java: warning: [unchecked] unchecked call to notifyObservers(T) as a member of the raw type com.foo.Observable
Is there a way to fix this, or should I just use @suppressWarnings ("unchecked")? Or maybe I should, like this safe method of calling?