let’s say i have this generic class which does some work and produces a result:
public abstract class Work<T> {
private T mResult;
public Work(T result) {
mResult = result;
}
public abstract <T> void doWork(T result);
public T getResult() {
return mResult;
}
}
For the users of this class i want type safety that would look something like this:
Work<MyResult> work = new Work<MyResult>(new MyResult()){
public void work(MyResult result){
//...
}
}
The problem is Java doesn’t work this way and forces me to cast from the generic type:
Work<MyResult> work = new Work<MyResult>(new MyResult()){
public <T> void work (T result){
// (MyResult)result - not nice
}
}
Is there a way to have type safety in a nice way like in the first example?
Thanks,
Teo
You don’t need the
<T>in the declaration ofdoWork, because you want to use the T that is declared at the class level – you needThe current declaration is the same as
it isn’t necessarily the same T as the rest of your class.