say your given an instance of List[Class[_ <: Base]]
, and say that many classes extends Base
:
class A extends Base
class B extends Base
class C extends A
etc'...
now, the given list may contain only some classes. e.g. : val classes = classOf[A] :: Nil
, well, how can i test when i get an instantiated val
if it's class is of type that is found in the list, or if it a subclass for a class in the list? i.e. how would you implement:
def testClass(class : List[Class[_ <: Base]], instance : Base) : Boolean
when:
val classes = classOf[A] :: Nil
testClass(classes, new A) // should return true
testClass(classes, new B) // should return false
testClass(classes, new C) // should return true
use case:
i'm trying to write a generic retry pattern, i.e. getting some code that is very error prone, and i want to retry executing it for some number of maximum tries, when every time it fails, it should execute some "wait" method.
e.g.
retryRequest({
//Some code that throws exceptions
}, classOf[SomeException] :: classOf[SomeOtherException] :: Nil,
100, {Thread.sleep(5000)})
well this works OK, but it won't test for subclasses of a given exception:
def retryRequest(req : => Unit, validExceptions : List[Class[_ <: java.lang.Throwable]], tries : Int, waitMethod : => Unit) {
var keepTrying = false
var tryCount = 0
do{
try{
logger.debug("retryRequest, try #" + tryCount)
keepTrying = false
req
}catch{
case ex if(tryCount >= tries && validExceptions.contains(ex.getClass)) => {
throw new MaxTriesReachedException("tried for " + tryCount + "times, but no luck. " +
"you may want to try ommitting generic exceptions types from the given list.")
}
case ex if (validExceptions.contains(ex.getClass)) => {
logger.debug("intercepted " + ex.toString)
tryCount += 1
keepTrying = true
waitMethod
}
}
}while(keepTrying)
}
i would realy want to replace:
validExceptions.contains(ex.getClass)
with something like:
validExceptions.exists(exClass => ex.isInstanceOf[exClass]) //won't compile
is it possible? how?