Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Generics scala中的反射和类型检查_Generics_Scala_Reflection - Fatal编程技术网

Generics scala中的反射和类型检查

Generics scala中的反射和类型检查,generics,scala,reflection,Generics,Scala,Reflection,我有下面的scala代码 def invokeMethods(instance: AnyRef, clazz: Class[_]) { assert(clazz.isInstance(instance) // <- is there a way to check this statically? for {method <- clazz.getDeclaredMethods if shouldInvoke(method) // if the met

我有下面的scala代码

def invokeMethods(instance: AnyRef, clazz: Class[_]) {
   assert(clazz.isInstance(instance)   // <- is there a way to check this statically? 

   for {method <- clazz.getDeclaredMethods
        if shouldInvoke(method) // if the method has appropriate signature
       } method.invoke(instance)
}

// overload for common case
def invokeMethods(instance: AnyRef) {
   invokeMethods(instance, instance.getClass)
}
def invokeMethods(实例:AnyRef,clazz:Class[\uz]){

assert(clazz.isInstance(instance)/下面的编译,是您要找的吗

object Test {
   def shouldInvoke(m: java.lang.reflect.Method) = true
   def invokeMethods[T <:AnyRef](instance: T, clazz: Class[_ <: T]) {
     for {method <- clazz.getDeclaredMethods
       if shouldInvoke(method)
     } method.invoke(instance)
   }

   def invokeMethods[T <: AnyRef](instance: T) {
     invokeMethods(instance, instance.getClass)
   }
}
对象测试{
def shouldInvoke(m:java.lang.reflect.Method)=true

DeF VoCoMeDeOD[t是很接近的。但是考虑下面的场景:A类;B类扩展{DEF FoW(){}};您提出的代码允许我调用Test.VoCoMeMeDoD[a](new a,类b[b]),这将导致运行时异常。我的问题是这是否可以在编译时检查。
object Test {
   def shouldInvoke(m: java.lang.reflect.Method) = true
   def invokeMethods[T <:AnyRef](instance: T, clazz: Class[_ <: T]) {
     for {method <- clazz.getDeclaredMethods
       if shouldInvoke(method)
     } method.invoke(instance)
   }

   def invokeMethods[T <: AnyRef](instance: T) {
     invokeMethods(instance, instance.getClass)
   }
}