首页 文章

Scala:如何检查动态加载的类是否实现了特征?

提问于
浏览
0

我正在尝试构建一个Scala应用程序,用户可以在其中加载实现由特征定义的接口的类,然后应用程序将使用该特性 .

例如,我的运营商特质

trait Operator {
    def operate(a: Int, b: Int): Int
}

由用户定义的类实现,在运行时加载,Add .

class Add {
  def operate(a: Int, b: Int): Int = a + b
}

应用程序如何检查此Add类是否实现了它知道的运算符特征?我希望能够在加载的类的实例上调用 operate .

我尝试过像这样的简单模式匹配

case op: Class[Operator] => op.newInstance()

但这似乎是基于特征名称而不是成员签名来检查实现 .

1 回答

  • 3

    首先,让我们清楚术语,你的 class Add 根本没有 implement 你定义的 Operator 特征 . 您不应该也不能使用明确定义的术语来表示与其实际含义相比的不同内容 .

    现在,你要找的是 structural types 而不是 traits .

    让我们定义 strucural type ,名称为 IsOperator

    type IsOperator = {
      def operate(a: Int, b: Int): Int
    }
    

    并让我们定义一些使用它的逻辑,

    def perform(a: Int, b: Int, o: IsOperator): Int = o.operate(a, b)
    

    现在,任何 object 或任何 class 的实例都确认 structural type IsOperate (有一个名为 operate 且类型为 (Int, Int) => Int 的方法)可以与 perform 一起使用 .

    object Add {
      def operate(a: Int, b: Int): Int = a + b
    }
    
    val sum = perform(1, 2, Add)
    // sum: Int = 3
    

相关问题