【发布时间】:2011-12-09 11:16:44
【问题描述】:
如何在运行时定义新类型?我有一个工厂方法需要创建this.type 带有标记接口的新实例。标记接口在编译时没有混入。我需要找到一种方法来在运行时。
我正在使用 Scala,但我认为答案将足以涵盖 Java 和 Scala。
trait Fruit {
def eat: this.type with Eaten = {
getClass.getConstructors()(0).newInstance(Array()).asInstanceOf[this.type];
// somehow this needs to return a new instance of this.type with the Eaten trait
// note that "Apple with Eaten" is not a type that exists at compile-time
}
}
trait Eaten // marker interface
class Apple extends Fruit
val apple1 = new Apple
val apple2 = a.eat // should return a new Apple with Eaten instance
def eater(eaten: Eaten) = ... // this function only accepts Eaten fruit
eater(apple1) // wont compile!
eater(apple2) // will compile!
【问题讨论】:
-
现在对 Scala 提出的要求可能太多了。另请参阅此问题stackoverflow.com/questions/4847869/…
标签: java scala reflection