Java general Observer mode to achieve the original type is not selected.
I'm currently trying to take advantage of the general implementation of observer mode in Java. I find it seems to work well, except that it generates unchecked call warnings, and I want to fix it if possible The implementation is as follows:
Interface, iobserveable 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);
}
}
}
}
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);
}
}
Every time notifyobservers is called, an unchecked call warning is issued The complete 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 solve this problem, or should I only use @ suppresswarnings ("unchecked")? Or maybe I should even, in fact, a safe method call?
Solution
You did not provide a type parameter for observable in the extensions clause of the subject Since you declared observable < T > in this course, you should declare:
public class Subject extends Observable<Subject> {
...
}
