在通用方法的实现中强制实现类型安全(Enforce type safety in the implementation of a generic method)
假设我有这个泛型类,它做了一些工作并产生了一个结果:
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; } }
对于这个类的用户,我希望类型安全看起来像这样:
Work<MyResult> work = new Work<MyResult>(new MyResult()){ public void work(MyResult result){ //... } }
问题是Java不能以这种方式工作并迫使我从泛型类型转换:
Work<MyResult> work = new Work<MyResult>(new MyResult()){ public <T> void work (T result){ // (MyResult)result - not nice } }
有没有办法像第一个例子那样以一种很好的方式使用类型安全?
谢谢,Teo
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
原文:https://stackoverflow.com/questions/13489306
更新时间:2022-06-22 11:06