在Scala中按类类型实现注册表

时间:2015-08-11 10:51:42

标签: java scala

我对scala很新,我想知道如何将表示基于类型的注册表的简单Java反射代码转换为scala:

public static interface IType {

}


public static interface IParser {

    public IType parse(byte[] msg);
}


public class Registry {
    private Map<Class<? extends IType>, Class<? extends IParser>> registry = new HashMap<Class<? extends IType>, Class<? extends IParser>>()
        {{
             // Init with types and parsers
        }};

    // Initiate new parser for the specified type
    public IParser getParser(Class<? extends IType> type) throws InstantiationException, IllegalAccessException {
        return registry.get(type).newInstance();
    }
}

1 个答案:

答案 0 :(得分:0)

  import scala.collection.mutable

  trait IType

  trait IParser {
    def parse(msg: Array[Byte]): IType
  }

  class Registry {
    private val registry = mutable.HashMap.empty[Class[T] forSome {type T <: IType}, Class[Z] forSome {type Z <: IParser}]

    def getParser(cl: Class[T] forSome {type T <: IType}) = {
      registry(cl).newInstance()
    }
  }

<强>更新

在评论Registry中提及的Kolmar类可以重写为:

  class Registry {
    private val registry = mutable.HashMap.empty[Class[_ <: IType], Class[_ <: IParser]]

    def getParser(cl: Class[_ <: IType]) = {
      registry(cl).newInstance()
    }

    def getParserT[T <: IType : ClassTag]: IParser = 
      getParser(classTag[T].runtimeClass.asSubclass(classOf[IType]))
  }

使用非常方便的方法def getParserT[T <: IType : ClassTag]: IParser只需要类型参数,您必须传递要实例化的类型。