【发布时间】:2011-10-21 11:09:55
【问题描述】:
我想使用泛型来定义给定方法抛出的业务异常(scala 方法将从 Java 调用,因此它必须在签名中)。
这是我在 Java 中的做法:
public interface BaseInterface<T, E extends Throwable> {
public T process(Class<E> wrapperExc) throws E;
}
public class ExcOne extends Exception {}
public class SubclassOne implements BaseInterface<String, ExcOne> {
@Override
public String process(Class<ExcOne> wrapperExc) throws ExcOne {
return null;
}
}
这是我在 Scala 中尝试过的:
class UsingGenerics[IN, OUT, E <: Throwable] {
//@throws(classOf[E]) - error: class type required but E found
def process(request: IN, wrapperExc: Class[E]): OUT = {
null.asInstanceOf[OUT]
}
}
和..
trait BaseTrait {
type Request
type Response
type BusinessException <: Throwable
//error: class type required but BaseTrait.this.BusinessException found
//@throws(classOf[BusinessException])
def process(request: Request): Response
}
class TraitImplementor extends BaseTrait {
type Request = Input
type Response = Output
type BusinessException = BizExc
def process(r: Request): Response = {
if (1 != 2) throw new BusinessException("Bang")
new Response
}
}
class Input
class Output
class BizExc(msg: String) extends Exception(msg)
Scala 代码中的两条注释行都无法编译。
如果有人能解释如何进行这项工作,我将不胜感激。
对我来说,'throw new BusinessException("Bang")' 表示类型别名 'BusinessException' 是编译时文字,因此我希望它可以与 classOf 一起使用。
如果事实证明无法做到这一点,我也希望能深入了解类型系统发生的情况或注释相对于类型替换的处理顺序。
【问题讨论】: