本文整理汇总了Scala中java.lang.reflect.InvocationTargetException类的典型用法代码示例。如果您正苦于以下问题:Scala InvocationTargetException类的具体用法?Scala InvocationTargetException怎么用?Scala InvocationTargetException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了InvocationTargetException类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ReflectiveDynamicAccess
//设置package包名称以及导入依赖的类
package akka.actor
import scala.collection.immutable
import java.lang.reflect.InvocationTargetException
import scala.reflect.ClassTag
import scala.util.Try
class ReflectiveDynamicAccess(val classLoader: ClassLoader) extends DynamicAccess {
override def getClassFor[T: ClassTag](fqcn: String): Try[Class[_ <: T]] =
Try[Class[_ <: T]]({
val c = Class.forName(fqcn, false, classLoader).asInstanceOf[Class[_ <: T]]
val t = implicitly[ClassTag[T]].runtimeClass
if (t.isAssignableFrom(c)) c else throw new ClassCastException(t + " is not assignable from " + c)
})
override def createInstanceFor[T: ClassTag](clazz: Class[_], args: immutable.Seq[(Class[_], AnyRef)]): Try[T] =
Try {
val types = args.map(_._1).toArray
val values = args.map(_._2).toArray
val constructor = clazz.getDeclaredConstructor(types: _*)
constructor.setAccessible(true)
val obj = constructor.newInstance(values: _*)
val t = implicitly[ClassTag[T]].runtimeClass
if (t.isInstance(obj)) obj.asInstanceOf[T] else throw new ClassCastException(clazz.getName + " is not a subtype of " + t)
} recover { case i: InvocationTargetException if i.getTargetException ne null ? throw i.getTargetException }
override def createInstanceFor[T: ClassTag](fqcn: String, args: immutable.Seq[(Class[_], AnyRef)]): Try[T] =
getClassFor(fqcn) flatMap { c ? createInstanceFor(c, args) }
override def getObjectFor[T: ClassTag](fqcn: String): Try[T] = {
val classTry =
if (fqcn.endsWith("$")) getClassFor(fqcn)
else getClassFor(fqcn + "$") recoverWith { case _ ? getClassFor(fqcn) }
classTry flatMap { c ?
Try {
val module = c.getDeclaredField("MODULE$")
module.setAccessible(true)
val t = implicitly[ClassTag[T]].runtimeClass
module.get(null) match {
case null ? throw new NullPointerException
case x if !t.isInstance(x) ? throw new ClassCastException(fqcn + " is not a subtype of " + t)
case x: T ? x
}
} recover { case i: InvocationTargetException if i.getTargetException ne null ? throw i.getTargetException }
}
}
}
示例2: getClassFor
//设置package包名称以及导入依赖的类
package knot.data.util
import java.lang.reflect.InvocationTargetException
import scala.reflect.ClassTag
import scala.util.Try
trait ReflectionAccessor {
def getClassFor[T: ClassTag](classLoader: ClassLoader, fullName: String): Try[Class[_ <: T]] = {
Try[Class[_ <: T]]({
val c = Class.forName(fullName, false, classLoader).asInstanceOf[Class[_ <: T]]
val t = implicitly[ClassTag[T]].runtimeClass
if (t.isAssignableFrom(c)) {
c
} else {
throw new ClassCastException(s"$t is not assignable from $c")
}
})
}
def createInstanceFor[T: ClassTag](clazz: Class[_]): Try[T] = {
Try {
val ctor = clazz.getDeclaredConstructor()
ctor.setAccessible(true)
val obj = ctor.newInstance()
val t = implicitly[ClassTag[T]].runtimeClass
if (t.isInstance(obj)) {
obj.asInstanceOf[T]
} else {
throw new ClassCastException(s"${clazz.getName} is not a subtype of $t")
}
} recover { case i: InvocationTargetException if i.getTargetException ne null => throw i.getTargetException }
}
}
示例3: getClassFor
//设置package包名称以及导入依赖的类
package knot.core.util
import java.lang.reflect.InvocationTargetException
import scala.reflect.ClassTag
import scala.util.Try
trait ReflectionAccessor {
def getClassFor[T: ClassTag](classLoader: ClassLoader, fullName: String): Try[Class[_ <: T]] = {
Try[Class[_ <: T]]({
val c = Class.forName(fullName, false, classLoader).asInstanceOf[Class[_ <: T]]
val t = implicitly[ClassTag[T]].runtimeClass
if (t.isAssignableFrom(c)) {
c
} else {
throw new ClassCastException(s"$t is not assignable from $c")
}
})
}
def createInstanceFor[T: ClassTag](clazz: Class[_]): Try[T] = {
Try {
val ctor = clazz.getDeclaredConstructor()
ctor.setAccessible(true)
val obj = ctor.newInstance()
val t = implicitly[ClassTag[T]].runtimeClass
if (t.isInstance(obj)) {
obj.asInstanceOf[T]
} else {
throw new ClassCastException(s"${clazz.getName} is not a subtype of $t")
}
} recover { case i: InvocationTargetException if i.getTargetException ne null => throw i.getTargetException }
}
}
示例4: ReflectiveDynamicAccess
//设置package包名称以及导入依赖的类
package akka.actor
import scala.collection.immutable
import java.lang.reflect.InvocationTargetException
import scala.reflect.ClassTag
import scala.util.Try
class ReflectiveDynamicAccess(val classLoader: ClassLoader) extends DynamicAccess {
override def getClassFor[T: ClassTag](fqcn: String): Try[Class[_ <: T]] =
Try[Class[_ <: T]]({
val c = Class.forName(fqcn, false, classLoader).asInstanceOf[Class[_ <: T]]
val t = implicitly[ClassTag[T]].runtimeClass
if (t.isAssignableFrom(c)) c else throw new ClassCastException(t + " is not assignable from " + c)
})
override def createInstanceFor[T: ClassTag](clazz: Class[_], args: immutable.Seq[(Class[_], AnyRef)]): Try[T] =
Try {
val types = args.map(_._1).toArray
val values = args.map(_._2).toArray
val constructor = clazz.getDeclaredConstructor(types: _*)
constructor.setAccessible(true)
val obj = constructor.newInstance(values: _*)
val t = implicitly[ClassTag[T]].runtimeClass
if (t.isInstance(obj)) obj.asInstanceOf[T] else throw new ClassCastException(clazz.getName + " is not a subtype of " + t)
} recover { case i: InvocationTargetException if i.getTargetException ne null ? throw i.getTargetException }
override def createInstanceFor[T: ClassTag](fqcn: String, args: immutable.Seq[(Class[_], AnyRef)]): Try[T] =
getClassFor(fqcn) flatMap { c ? createInstanceFor(c, args) }
override def getObjectFor[T: ClassTag](fqcn: String): Try[T] = {
val classTry =
if (fqcn.endsWith("$")) getClassFor(fqcn)
else getClassFor(fqcn + "$") recoverWith { case _ ? getClassFor(fqcn) }
classTry flatMap { c ?
Try {
val module = c.getDeclaredField("MODULE$")
module.setAccessible(true)
val t = implicitly[ClassTag[T]].runtimeClass
module.get(null) match {
case null ? throw new NullPointerException
case x if !t.isInstance(x) ? throw new ClassCastException(fqcn + " is not a subtype of " + t)
case x: T ? x
}
} recover { case i: InvocationTargetException if i.getTargetException ne null ? throw i.getTargetException }
}
}
}
示例5: AndroidUtil
//设置package包名称以及导入依赖的类
package one.lockstep.vault.spi.impl.android
import java.io.InputStream
import java.lang.reflect.InvocationTargetException
import one.lockstep.util.Logging
import android.content.Context
import android.content.res.AssetManager
object AndroidUtil extends Logging {
def currentApplication: Context =
try {
val activityThreadClass = Class.forName("android.app.ActivityThread")
val currentApplicationMethod = activityThreadClass.getMethod("currentApplication")
val currentApplication = currentApplicationMethod.invoke(null).asInstanceOf[Context]
currentApplication
} catch {
case [email protected](_: ClassNotFoundException | _: NoSuchMethodException |
_: IllegalAccessException | _: InvocationTargetException) =>
throw new RuntimeException("failed to determine current application context", cause)
}
def openAsset(context: Context, assetName: String): InputStream =
context.getAssets.open(assetName, AssetManager.ACCESS_BUFFER)
def assetExists(context: Context, assetName: String): Boolean = {
val segments = assetName.split("/")
val (path, name) = (segments.init.mkString("/"), segments.last)
context.getAssets.list(path).contains(name)
}
}
示例6: invoke
//设置package包名称以及导入依赖的类
package com.atomist.rug.spi
import java.lang.reflect.InvocationTargetException
import com.atomist.rug.RugRuntimeException
import com.atomist.rug.runtime.js.interop.NashornUtils
import com.atomist.tree.TreeNode
import com.atomist.tree.content.text.OutOfDateNodeException
def invoke(target: Object, rawArgs: Seq[AnyRef]): Object = {
val args = rawArgs.map(a => NashornUtils.toJavaType(a))
// Include TreeNode methods, although the annotations won't be inherited
val methods = target.getClass.getMethods.toSeq.filter(m =>
this.name.equals(m.getName) &&
(m.getDeclaredAnnotations.exists(_.isInstanceOf[ExportFunction]) || TreeNodeOperations.contains(m.getName)) &&
this.parameters.size == m.getParameterCount
)
if (methods.size != 1)
throw new IllegalArgumentException(
s"Operation [$name] cannot be invoked on [${target.getClass.getName}]: Found ${methods.size} definitions with ${parameters.size}, required exactly 1: " +
s"Known methods=[${methods.mkString(",")}]"
)
try {
methods.head.invoke(target, args: _*)
} catch {
case e: InvocationTargetException if e.getCause.isInstanceOf[OutOfDateNodeException] => throw e.getCause // we meant to do this
case t: Throwable =>
val argDiagnostics = args map {
case null => "null"
case o => s"$o: ${o.getClass}"
}
throw new RugRuntimeException(null, s"Exception invoking ${methods.head} with args=${argDiagnostics.mkString(",")}: ${t.getMessage}", t)
}
}
}
object TypeOperation {
val TreeNodeAllTypeOperations: Seq[TypeOperation] =
new ReflectiveTypeOperationFinder(classOf[TreeNode]).allOperations
val TreeNodeTypeOperations: Seq[TypeOperation] =
new ReflectiveTypeOperationFinder(classOf[TreeNode]).operations
val TreeNodeType = new Typed {
override val name = "TreeNode"
override def description: String = "TreeNode operations"
override def allOperations = TreeNodeAllTypeOperations
override def operations = TreeNodeTypeOperations
}
val TreeNodeOperations: Set[String] =
TreeNodeAllTypeOperations.map(_.name).toSet
}
示例7: FlinkProcessTestRunner
//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.engine.management
import java.io.File
import java.lang.reflect.InvocationTargetException
import com.typesafe.config.Config
import pl.touk.nussknacker.engine.api.deployment.test.{TestData, TestResults}
import pl.touk.nussknacker.engine.util.ThreadUtils
import pl.touk.nussknacker.engine.util.loader.JarClassLoader
import scala.reflect.runtime.{universe => ru}
object FlinkProcessTestRunner {
def apply(config: Config, jarFile: File) = {
new FlinkProcessTestRunner(config, JarClassLoader(jarFile))
}
}
class FlinkProcessTestRunner(config: Config, jarClassLoader: JarClassLoader) {
private val invoker: ru.MethodMirror = {
val m = ru.runtimeMirror(jarClassLoader.classLoader)
val module = m.staticModule("pl.touk.nussknacker.engine.process.runner.FlinkTestMain")
val im = m.reflectModule(module)
val method = im.symbol.info.decl(ru.TermName("run")).asMethod
val objMirror = m.reflect(im.instance)
objMirror.reflectMethod(method)
}
def test(processId: String, json: String, testData: TestData): TestResults = {
//we have to use context loader, as in UI we have don't have nussknacker-process on classpath...
ThreadUtils.withThisAsContextClassLoader(jarClassLoader.classLoader) {
tryToInvoke(testData, json).asInstanceOf[TestResults]
}
}
def tryToInvoke(testData: TestData, json: String): Any = try {
invoker(json, config, testData, List(jarClassLoader.jarUrl))
} catch {
case e: InvocationTargetException => throw e.getTargetException
}
}
示例8: ExecutorProxy
//设置package包名称以及导入依赖的类
package com.programmaticallyspeaking.ncd.infra
import java.lang.reflect.{InvocationHandler, InvocationTargetException, Method}
import java.util.concurrent.Executor
import org.slf4s.Logging
import scala.concurrent.{Await, Future, Promise}
import scala.reflect.ClassTag
import scala.concurrent.duration._
import scala.util.{Failure, Success, Try}
class ExecutorProxy(executor: Executor) {
def createFor[A <: AnyRef : ClassTag](instance: A): A = {
val clazz = implicitly[ClassTag[A]].runtimeClass
java.lang.reflect.Proxy.newProxyInstance(clazz.getClassLoader, Array(clazz), new Handler(instance)).asInstanceOf[A]
}
class Handler(instance: AnyRef) extends InvocationHandler with Logging {
import scala.concurrent.ExecutionContext.Implicits._
private val className = instance.getClass.getName
override def invoke(proxy: scala.Any, method: Method, args: Array[AnyRef]): AnyRef = {
val resultPromise = Promise[AnyRef]()
val before = System.nanoTime()
executor.execute(() => {
Try(method.invoke(instance, args: _*)) match {
case Success(f: Future[AnyRef]) => resultPromise.completeWith(f)
case Success(result) => resultPromise.success(result)
case Failure(t: InvocationTargetException) => resultPromise.failure(t.getCause)
case Failure(t) => resultPromise.failure(t)
}
})
resultPromise.future.onComplete { _ =>
val methodName = method.getName
val millis = (System.nanoTime() - before).nanos.toMillis
log.trace(s"Elapsed time for $className.$methodName = $millis ms")
}
if (classOf[Future[_]].isAssignableFrom(method.getReturnType)) resultPromise.future
else Await.result(resultPromise.future, 30.seconds) //TODO: Configurable
}
}
}
示例9: LinkedRouteV2
//设置package包名称以及导入依赖的类
package webby.route.v2
import java.lang.reflect.{InvocationTargetException, Method}
import java.util.regex.{Matcher, Pattern}
import io.netty.handler.codec.http.HttpMethod
import webby.api.mvc.Handler
import webby.route.{DomainProvider, Var}
class LinkedRouteV2(val name: String,
val domainProvider: DomainProvider[_],
val method: HttpMethod,
val basePath: String,
val pattern: Pattern,
routeLinksForDomainData: (Any) => RouteHandlers,
val vars: Vector[Var[_]],
val varIndices: Vector[Int],
val linkMethod: Method) {
require(!vars.contains(null), "All variables must be used in url. " + toString)
require(varIndices.size == linkMethod.getParameterTypes.size, "Method argument count mismatch. Seems method with the same name already exists. You should rename it, or make it final. " + toString)
def resolve(domain: Any, m: Matcher): Option[Handler] = {
val routeLinks = routeLinksForDomainData(domain)
var i: Int = 0
val ln = varIndices.size
val args = Array.ofDim[AnyRef](ln)
while (i < ln) {
val group: String = m.group(varIndices(i) + 1)
val vr: Var[_] = vars(i)
try {
args(i) = vr.fromString(group).asInstanceOf[AnyRef]
} catch {
// ?????? ??? ???????? ???????? (??? ???????, ??? NumberFormatException, ????? ????? ??????? ??????? ??? int).
case e: Throwable => return None
}
i += 1
}
try {
Some(linkMethod.invoke(routeLinks, args: _*).asInstanceOf[Handler])
} catch {
case e: InvocationTargetException => throw e.getCause
}
}
override def toString: String = method.name() + " (" + basePath + ") " + pattern + " - " + name
}
示例10: CircuitBreakerHandler
//设置package包名称以及导入依赖的类
package com.unstablebuild.autobreaker
import java.lang.reflect.{InvocationHandler, InvocationTargetException, Method}
import akka.actor.Scheduler
import com.typesafe.scalalogging.StrictLogging
import scala.concurrent.{ExecutionContext, Future}
import scala.{Proxy => BaseProxy}
class CircuitBreakerHandler(val self: Any, breaker: AutoBreaker)(implicit ec: ExecutionContext, scheduler: Scheduler)
extends InvocationHandler
with BaseProxy
with StrictLogging {
private val future = classOf[Future[_]]
override def invoke(proxy: Any, method: Method, args: Array[AnyRef]): AnyRef = {
def callMethod: AnyRef = method.invoke(self, args: _*)
try {
method.getReturnType match {
case `future` if canWrap(method) =>
breaker.call(future.cast(callMethod))
case _ =>
callMethod
}
} catch {
case e: InvocationTargetException => throw e.getTargetException
}
}
private def canWrap(method: Method): Boolean =
!self.getClass.getMethod(method.getName, method.getParameterTypes: _*).isAnnotationPresent(classOf[NoCircuitBreaker])
}