• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Method类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中java.lang.reflect.Method的典型用法代码示例。如果您正苦于以下问题:Scala Method类的具体用法?Scala Method怎么用?Scala Method使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Method类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: ClassPathExistsException

//设置package包名称以及导入依赖的类
package com.galacticfog.gestalt.lambda.impl

import java.io.File

import java.io.IOException
import java.lang.reflect.Method
import java.net.URL
import java.net.URLClassLoader
import java.util.Iterator
import java.util.ServiceLoader

case class ClassPathExistsException( msg : String ) extends Exception

object DynLoader {

  def extendClasspath( dir : File, inLoader : ClassLoader ) = {
    try {

      val sysLoader : URLClassLoader = inLoader match {
        case u : URLClassLoader => u
        case _ => throw new Exception( "Cast Exception" )
      }

      val urls : Seq[URL] = sysLoader.getURLs()
      val udir = dir.toURI().toURL()

      val udirs = udir.toString()
      urls.find( u => u.toString().equalsIgnoreCase(udirs) ) match {
        case Some(s) => throw new ClassPathExistsException( "class path exists" )
        case None => {}
      }

      val sysClass = classOf[URLClassLoader]

      val method : Method = sysClass.getDeclaredMethod("addURL", classOf[URL] )
      method.setAccessible(true)
      val udirObj = udir match {
        case o : Object => o
        case _ => throw new Exception( "impossible" )
      }

      method.invoke(sysLoader, udirObj )
      println( "Loaded " + udirs + " dynamically...")
    }
    catch {
      case cpe : ClassPathExistsException => {
        println( "class path exists, ignoring" )
      }
      case t : Throwable  => {
        t.printStackTrace();
      }
    }
  }
} 
开发者ID:GalacticFog,项目名称:gestalt-lambda,代码行数:55,代码来源:DynLoader.scala


示例2: ModuleGrammar

//设置package包名称以及导入依赖的类
package com.containant


class ModuleGrammar(module: Module) extends LBNF {
  import java.lang.reflect.Method
  override type Sort = Class[_]
  override type Label = Method
  
  private val providers: List[Method] =
    module.getClass.getMethods.toList.sortBy(_.getName).filter { m => 
      !List( "equals","hashCode","toString", "getClass",
            "wait", "notify", "notifyAll"
           ).contains(m.getName)
    }
  
  override def sort(label: Label): Sort =
    label.getReturnType
  
  override val sorts: Seq[Sort] = 
    providers.map(sort).distinct
  
  override def labels(sort: Sort): Seq[Label] =
    providers.filter { p => sort.isAssignableFrom(p.getReturnType) }
  
  override def rule(label: Label): Seq[Sort] = 
    label.getParameterTypes
    
    
  def construct(tree: SyntaxTree): Object = {
    val arguments = tree.subtrees.map(construct)
    tree.label.invoke(module, arguments:_*)
  }
} 
开发者ID:zaklogician,项目名称:ContainAnt,代码行数:34,代码来源:ModuleGrammar.scala


示例3: ReflectiveFunctionExport

//设置package包名称以及导入依赖的类
package com.atomist.rug.spi

import java.lang.reflect.Method

import org.springframework.util.ReflectionUtils


object ReflectiveFunctionExport {

  def allExportedOperations(c: Class[_]): Seq[TypeOperation] =
    if (c == null) Nil
    else operations(ReflectionUtils.getAllDeclaredMethods(c))

  def exportedOperations(c: Class[_]): Seq[TypeOperation] =
    if (c == null) Nil
    else operations(c.getDeclaredMethods)

  private def operations(methods: Array[Method]) =
    methods
      .filter(_.getAnnotations.exists(_.isInstanceOf[ExportFunction]))
      .map(m => {
        val a = m.getAnnotation(classOf[ExportFunction])
        val params = extractExportedParametersAndDocumentation(m)
        TypeOperation(m.getName, a.description(),
          a.readOnly(),
          params,
          SimpleParameterOrReturnType.fromJavaType(m.getGenericReturnType),
          m.getDeclaringClass,
          a.example() match {
            case "" => None
            case ex => Some(ex)
          },
          exposeAsProperty = a.exposeAsProperty(),
          exposeResultDirectlyToNashorn = a.exposeResultDirectlyToNashorn(),
          deprecated = m.isAnnotationPresent(classOf[Deprecated]))
      })

  private def extractExportedParametersAndDocumentation(m: Method): Array[TypeParameter] = {
    m.getParameters.map(p =>
      if (p.isAnnotationPresent(classOf[ExportFunctionParameterDescription])) {
        val annotation = p.getDeclaredAnnotation(classOf[ExportFunctionParameterDescription])
        TypeParameter(annotation.name(),
          SimpleParameterOrReturnType.fromJavaType(p.getParameterizedType),
          Some(annotation.description()))
      }
      else
        TypeParameter(p.getName,
          SimpleParameterOrReturnType.fromJavaType(p.getParameterizedType),
          None)
    )
  }

} 
开发者ID:atomist,项目名称:rug,代码行数:54,代码来源:ReflectiveFunctionExport.scala


示例4: DefaultMetricNamer

//设置package包名称以及导入依赖的类
package de.khamrakulov.play.metrics.annotation

import java.lang.reflect.Method

import com.codahale.metrics.MetricRegistry.{name => MetricName}
import com.codahale.metrics.annotation._


object DefaultMetricNamer {
  private[annotation] val COUNTER_SUFFIX: String = "counter"
  private[annotation] val COUNTER_SUFFIX_MONOTONIC: String = "current"
  private[annotation] val GAUGE_SUFFIX: String = "gauge"
  private[annotation] val METERED_SUFFIX: String = "meter"
  private[annotation] val TIMED_SUFFIX: String = "timer"
}

class DefaultMetricNamer extends MetricNamer {
  def counted(method: Method, counted: Counted): String = if (counted.absolute) {
    counted.name
  } else if (counted.name.isEmpty) {
    if (counted.monotonic) MetricName(method.getDeclaringClass, method.getName, DefaultMetricNamer.COUNTER_SUFFIX_MONOTONIC)
    else MetricName(method.getDeclaringClass, method.getName, DefaultMetricNamer.COUNTER_SUFFIX)
  } else {
    MetricName(method.getDeclaringClass, counted.name)
  }

  def metered(method: Method, exceptionMetered: ExceptionMetered): String = if (exceptionMetered.absolute) {
    exceptionMetered.name
  } else if (exceptionMetered.name.isEmpty) {
    MetricName(method.getDeclaringClass, method.getName, ExceptionMetered.DEFAULT_NAME_SUFFIX)
  } else {
    MetricName(method.getDeclaringClass, exceptionMetered.name)
  }

  def gauge(method: Method, gauge: Gauge): String = if (gauge.absolute) {
    gauge.name
  } else if (gauge.name.isEmpty) {
    MetricName(method.getDeclaringClass, method.getName, DefaultMetricNamer.GAUGE_SUFFIX)
  } else {
    MetricName(method.getDeclaringClass, gauge.name)
  }

  def metered(method: Method, metered: Metered): String = if (metered.absolute) {
    metered.name
  } else if (metered.name.isEmpty) {
    MetricName(method.getDeclaringClass, method.getName, DefaultMetricNamer.METERED_SUFFIX)
  } else {
    MetricName(method.getDeclaringClass, metered.name)
  }

  def timed(method: Method, timed: Timed): String = if (timed.absolute) {
    timed.name
  } else if (timed.name.isEmpty) {
    MetricName(method.getDeclaringClass, method.getName, DefaultMetricNamer.TIMED_SUFFIX)
  } else {
    MetricName(method.getDeclaringClass, timed.name)
  }
} 
开发者ID:htimur,项目名称:metrics-annotation-play,代码行数:59,代码来源:MetricNamer.scala


示例5: ExceptionMeteredListener

//设置package包名称以及导入依赖的类
package de.khamrakulov.play.metrics.annotation.guice.listener

import java.lang.reflect.Method

import com.codahale.metrics.MetricRegistry
import com.codahale.metrics.annotation.ExceptionMetered
import de.khamrakulov.play.metrics.annotation.MetricNamer
import de.khamrakulov.play.metrics.annotation.guice.interceptor.ExceptionMeteredInterceptor
import de.khamrakulov.play.metrics.annotation.matcher.AnnotationProvider


private[annotation] object ExceptionMeteredListener {
  def apply(metricRegistry: MetricRegistry, metricNamer: MetricNamer, provider: AnnotationProvider) =
    new ExceptionMeteredListener(metricRegistry, metricNamer, provider)
}

private[annotation] class ExceptionMeteredListener(metricRegistry: MetricRegistry,
                                              metricNamer: MetricNamer,
                                              provider: AnnotationProvider) extends DeclaredMethodsTypeListener {

  protected def getInterceptor(method: Method) = provider.get[ExceptionMetered].from(method).map { annotation =>
    val meter = metricRegistry.meter(metricNamer.metered(method, annotation))
    ExceptionMeteredInterceptor(meter, annotation.cause)
  }

} 
开发者ID:htimur,项目名称:metrics-annotation-play,代码行数:27,代码来源:ExceptionMeteredListener.scala


示例6: CountedListener

//设置package包名称以及导入依赖的类
package de.khamrakulov.play.metrics.annotation.guice.listener

import java.lang.reflect.Method

import com.codahale.metrics.MetricRegistry
import com.codahale.metrics.annotation.Counted
import de.khamrakulov.play.metrics.annotation.MetricNamer
import de.khamrakulov.play.metrics.annotation.guice.interceptor.CountedInterceptor
import de.khamrakulov.play.metrics.annotation.matcher.AnnotationProvider


private[annotation] object CountedListener {
  def apply(metricRegistry: MetricRegistry, metricNamer: MetricNamer, provider: AnnotationProvider) =
    new CountedListener(metricRegistry, metricNamer, provider)
}

private[annotation] class CountedListener(metricRegistry: MetricRegistry,
                                     metricNamer: MetricNamer,
                                     provider: AnnotationProvider) extends DeclaredMethodsTypeListener {

  protected def getInterceptor(method: Method) = {
    provider.get[Counted].from(method).map { annotation =>
      val counter = metricRegistry.counter(metricNamer.counted(method, annotation))
      CountedInterceptor(counter, annotation)
    }
  }

} 
开发者ID:htimur,项目名称:metrics-annotation-play,代码行数:29,代码来源:CountedListener.scala


示例7: MeteredListener

//设置package包名称以及导入依赖的类
package de.khamrakulov.play.metrics.annotation.guice.listener

import java.lang.reflect.Method

import com.codahale.metrics.MetricRegistry
import com.codahale.metrics.annotation.Metered
import de.khamrakulov.play.metrics.annotation.MetricNamer
import de.khamrakulov.play.metrics.annotation.guice.interceptor.MeteredInterceptor
import de.khamrakulov.play.metrics.annotation.matcher.AnnotationProvider


private[annotation] object MeteredListener {
  def apply(registry: MetricRegistry, namer: MetricNamer, provider: AnnotationProvider) =
    new MeteredListener(registry, namer, provider)
}

private[annotation] class MeteredListener(registry: MetricRegistry, namer: MetricNamer, provider: AnnotationProvider)
  extends DeclaredMethodsTypeListener {

  protected def getInterceptor(method: Method) = provider.get[Metered].from(method).map { annotation =>
    MeteredInterceptor(registry.meter(namer.metered(method, annotation)))
  }
} 
开发者ID:htimur,项目名称:metrics-annotation-play,代码行数:24,代码来源:MeteredListener.scala


示例8: GaugeInjectionListener

//设置package包名称以及导入依赖的类
package de.khamrakulov.play.metrics.annotation.guice.listener

import java.lang.reflect.Method

import com.codahale.metrics.{Gauge, MetricRegistry}
import com.google.inject.spi.InjectionListener


private[annotation] object GaugeInjectionListener {
  def apply(metricRegistry: MetricRegistry, metricName: String, method: Method) =
    new GaugeInjectionListener(metricRegistry, metricName, method)
}

private[annotation] class GaugeInjectionListener[I](metricRegistry: MetricRegistry, metricName: String, method: Method) extends InjectionListener[I] {
  def afterInjection(i: I) = if (metricRegistry.getGauges.get(metricName) == null) {
    metricRegistry.register(metricName, new Gauge[AnyRef]() {
      def getValue = try method.invoke(i) catch {
        case e: Exception => new RuntimeException(e)
      }
    })
  }
} 
开发者ID:htimur,项目名称:metrics-annotation-play,代码行数:23,代码来源:GaugeInjectionListener.scala


示例9: get

//设置package包名称以及导入依赖的类
package de.khamrakulov.play.metrics.annotation.matcher

import java.lang.annotation.Annotation
import java.lang.reflect.Method


trait AnnotationMatcher {
  def get[T <: Annotation: Manifest](method: Method): Option[T]
}

object ClassAnnotationMatcher {
  def apply() = new ClassAnnotationMatcher()
}

class ClassAnnotationMatcher() extends AnnotationMatcher {
  override def get[T <: Annotation](method: Method)(implicit ev: Manifest[T]): Option[T] = Option {
    method.getDeclaringClass.getAnnotation(ev.runtimeClass.asInstanceOf[Class[T]])
  }
}

object MethodAnnotationMatcher {
  def apply() = new MethodAnnotationMatcher()
}

class MethodAnnotationMatcher() extends AnnotationMatcher {
  override def get[T <: Annotation](method: Method)(implicit ev: Manifest[T]): Option[T] = Option {
    method.getAnnotation(ev.runtimeClass.asInstanceOf[Class[T]])
  }
} 
开发者ID:htimur,项目名称:metrics-annotation-play,代码行数:30,代码来源:AnnotationMatcher.scala


示例10: 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
    }
  }
} 
开发者ID:provegard,项目名称:ncdbg,代码行数:48,代码来源:ExecutorProxy.scala


示例11: SslShutdownHandler

//设置package包名称以及导入依赖的类
package com.twitter.finagle.ssl

import java.lang.reflect.Method
import java.util.logging.Logger
import javax.net.ssl.SSLException

import org.jboss.netty.channel.{
  ChannelHandlerContext, ChannelStateEvent, ExceptionEvent, SimpleChannelUpstreamHandler
}

class SslShutdownHandler(o: Object) extends SimpleChannelUpstreamHandler {
  private[this] val log = Logger.getLogger(getClass().getName())
  private[this] val shutdownMethod: Option[Method] =
    try {
      Some(o.getClass().getMethod("shutdown"))
    } catch {
      case _: NoSuchMethodException => None
    }

  private[this] def shutdownAfterChannelClosure() {
    shutdownMethod foreach { method: Method =>
      method.invoke(o)
    }
  }

  override def exceptionCaught(ctx: ChannelHandlerContext, e: ExceptionEvent) {
    // remove the ssl handler so that it doesn't trap the disconnect
    if (e.getCause.isInstanceOf[SSLException])
      ctx.getPipeline.remove("ssl")

    super.exceptionCaught(ctx, e)
  }

  override def channelClosed(ctx: ChannelHandlerContext, e: ChannelStateEvent) {
    shutdownAfterChannelClosure()

    super.channelClosed(ctx, e)
  }
} 
开发者ID:deenar,项目名称:fintest,代码行数:40,代码来源:SslShutdownHandler.scala


示例12: ConsoleRun

//设置package包名称以及导入依赖的类
package webby.mvc

import java.lang.reflect.Method

import webby.api.Profile


object ConsoleRun {

  def main(args: Array[String]) {
    if (args.length < 1 || args.length > 2) {
      println("Usage: webby webby.mvc.ConsoleRun module.Class methodName")
      sys.exit(-1)
    }
    val className = args(0)
    val methodName = args(1)

    val classLoader: ClassLoader = Thread.currentThread().getContextClassLoader
    val cls: Class[_] = classLoader.loadClass(className)
    val method: Method = cls.getMethod(methodName)
    AppStub.withApp(Profile.Console) {
      val result: AnyRef = method.invoke(cls)
      if (result != null) {
        println(result)
      }
    }
  }
} 
开发者ID:citrum,项目名称:webby,代码行数:29,代码来源:ConsoleRun.scala


示例13: 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
} 
开发者ID:citrum,项目名称:webby,代码行数:47,代码来源:LinkedRouteV2.scala


示例14: ConstructorParameter

//设置package包名称以及导入依赖的类
package com.kakao.shaded.jackson.module.scala
package introspect

import util.Implicits._
import java.lang.reflect.{AccessibleObject, Constructor, Field, Method}

import scala.language.existentials

case class ConstructorParameter(constructor: Constructor[_], index: Int, defaultValueMethod: Option[Method])

case class PropertyDescriptor(name: String,
                              param: Option[ConstructorParameter],
                              field: Option[Field],
                              getter: Option[Method],
                              setter: Option[Method],
                              beanGetter: Option[Method],
                              beanSetter: Option[Method])
{
  if (List(field, getter).flatten.isEmpty) throw new IllegalArgumentException("One of field or getter must be defined.")

  def findAnnotation[A <: java.lang.annotation.Annotation](implicit mf: Manifest[A]): Option[A] = {
    val cls = mf.runtimeClass.asInstanceOf[Class[A]]
    lazy val paramAnnotation = (param flatMap { cp =>
      val paramAnnos = cp.constructor.getParameterAnnotations
      paramAnnos(cp.index).find(cls.isInstance)
    }).asInstanceOf[Option[A]]
    val getAnno = (o: AccessibleObject) => o.getAnnotation(cls)
    lazy val fieldAnnotation = field optMap getAnno
    lazy val getterAnnotation = getter optMap getAnno
    lazy val beanGetterAnnotation = beanGetter optMap getAnno

    paramAnnotation orElse fieldAnnotation orElse getterAnnotation orElse beanGetterAnnotation
  }

} 
开发者ID:kakao,项目名称:mango,代码行数:36,代码来源:PropertyDescriptor.scala


示例15: apply

//设置package包名称以及导入依赖的类
package com.kakao.mango.reflect

import java.lang.reflect.{Method, Constructor}

import scala.reflect.runtime.universe._
import scala.util.control.NonFatal


  def apply(obj: AnyRef, method: Method): Array[AnyRef] = {
    val clazz = method.getDeclaringClass
    val name = method.getName

    val count = method.getParameterTypes.length
    val result = new Array[AnyRef](count)

    try {
      for (i <- 0 until count) {
        util.Try(clazz.getMethod(s"$name$$default$$${i+1}")).foreach { method =>
          result(i) = method.invoke(obj)
        }
      }
    } catch {
      case NonFatal(e) => // if there is no default parameters, return the array with null entries
    }

    result
  }

} 
开发者ID:kakao,项目名称:mango,代码行数:30,代码来源:DefaultParameters.scala


示例16: Accessible

//设置package包名称以及导入依赖的类
package com.kakao.mango.reflect

import java.lang.reflect.{Constructor, Method, Field}
import java.lang.reflect.Modifier._

import scala.reflect._


object Accessible {

  val modifiers: Field = {
    val field = classOf[Field].getDeclaredField("modifiers")
    field.setAccessible(true)
    field
  }

  def field[T: ClassTag](name: String): Field = {
    field(classTag[T].runtimeClass, name)
  }

  def field(clazz: Class[_], name: String): Field = {
    val field = clazz.getDeclaredField(name)
    field.setAccessible(true)
    modifiers.setInt(field, field.getModifiers & ~FINAL)
    field
  }

  def method[T: ClassTag](name: String, parameterTypes: Class[_]*): Method = {
    method(classTag[T].runtimeClass, name, parameterTypes: _*)
  }

  def method(clazz: Class[_], name: String, parameterTypes: Class[_]*): Method = {
    val method = clazz.getDeclaredMethod(name, parameterTypes: _*)
    method.setAccessible(true)
    method
  }

  def constructor[T](clazz: Class[T], parameterTypes: Class[_]*): Constructor[T] = {
    val constructor = clazz.getDeclaredConstructor(parameterTypes: _*)
    constructor.setAccessible(true)
    constructor
  }

  def firstConstructor[T: ClassTag]: Constructor[T] = {
    firstConstructor(classTag[T].runtimeClass.asInstanceOf[Class[T]])
  }

  def firstConstructor[T](clazz: Class[T]): Constructor[T] = {
    val constructor = clazz.getDeclaredConstructors()(0).asInstanceOf[Constructor[T]]
    constructor.setAccessible(true)
    constructor
  }

} 
开发者ID:kakao,项目名称:mango,代码行数:55,代码来源:Accessible.scala


示例17: BehaviorImpl

//设置package包名称以及导入依赖的类
package dcos.metronome.behavior.impl

import java.lang.reflect.Method

import com.softwaremill.macwire.aop.{ Interceptor, ProxyingInterceptor }
import dcos.metronome.behavior.{ BehaviorConfig, Behavior, Metrics }
import nl.grons.metrics.scala.{ Meter, Timer }
import org.slf4j.LoggerFactory

import scala.concurrent.Future
import scala.reflect.ClassTag
import scala.util.control.NonFatal

class BehaviorImpl(val config: BehaviorConfig, val metrics: Metrics) extends Behavior {

  private[this] val log = LoggerFactory.getLogger(getClass)

  override def apply[T <: AnyRef](t: T)(implicit classTag: ClassTag[T]): T = {
    if (config.withMetrics) timedInvocationWithExceptionCount(classTag).apply(t) else t
  }

  def timedInvocationWithExceptionCount[T](classTag: ClassTag[T]): Interceptor = {
    val builder = metrics.builder(classTag)
    var methodTimer = Map.empty[String, Timer]
    def timer(method: Method): Timer = {
      methodTimer.getOrElse(method.getName, {
        log.debug(s"Create new timer for method: ${method.getName} in class ${classTag.runtimeClass.getName}")
        val timer = builder.timer(s"time.${method.getName}")
        methodTimer += method.getName -> timer
        timer
      })
    }
    var methodExceptionCount = Map.empty[String, Meter]
    def methodException(method: Method, ex: Throwable): Meter = {
      val name = s"exception.${method.getName}.${ex.getClass.getName}"
      methodExceptionCount.getOrElse(name, {
        log.debug(s"Create new count for method: ${method.getName} exception: ${ex.getClass.getName} in class ${classTag.runtimeClass.getName}")
        val meter = builder.meter(name)
        methodExceptionCount += name -> meter
        meter
      })
    }
    ProxyingInterceptor.apply { ctx =>
      val metricTimer = timer(ctx.method)
      if (ctx.method.getReturnType.isAssignableFrom(classOf[Future[Any]])) {
        import mesosphere.util.CallerThreadExecutionContext.callerThreadExecutionContext
        metricTimer.timeFuture(ctx.proceed().asInstanceOf[Future[Any]]).recover {
          case NonFatal(ex: Throwable) =>
            methodException(ctx.method, ex).mark()
            throw ex
        }
      } else {
        metricTimer.time(ctx.proceed())
      }
    }
  }
} 
开发者ID:dcos,项目名称:metronome,代码行数:58,代码来源:BehaviorImpl.scala


示例18: 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])

} 
开发者ID:lucastorri,项目名称:autobreaker,代码行数:38,代码来源:CircuitBreakerHandler.scala


示例19: DefaultCommandLineExecutor

//设置package包名称以及导入依赖的类
package org.quicli.executor

import java.lang.reflect.{Field, Method}

import org.quicli.converters.ConvertOpts
import org.quicli.model.CommandDesc.ReflectInfo
import org.quicli.model._
import org.quicli.parser.LineParser
import org.quicli.parser.impl.DefaultLineParser
import org.quicli.{QuicliApp, _}


class DefaultCommandLineExecutor extends CommandLineExecutor {

  private val lineParser: LineParser = new DefaultLineParser

  override def execute(line: Seq[String])(implicit app: QuicliApp): Any = {
    val cl: CommandLine = lineParser.parse(line)
    invokeCommand(cl.command, cl.args)
  }

  private def invokeCommand(cmd: CommandDesc, args: Args): Any = {
    val refInfo: ReflectInfo = cmd.reflectInfo
    val execMethod: Method = refInfo.execMethod
    val cmdInstance: Any = refInfo.clazz.newInstance()

    if (args.nonEmpty) {
      setCommandArgs(cmd, args, cmdInstance)
    }

    execMethod.invoke(cmdInstance)
  }

  private def setCommandArgs(cmd: CommandDesc, args: Args, cmdInstance: Any): Unit = {
    val params: Parameters = cmd.parameters

    params.maybeDefaultParam.foreach { defaultParam =>
      setParamValue(defaultParam, args.positionalArg, cmdInstance)
    }
  }

  private def setParamValue(param: ParameterDesc,
                            arg: Arg,
                            cmdInstance: Any): Unit = {
    if (arg.isEmpty) return

    val convertedValue: Any = param.arity match {
      case Arity.Single =>
        param.converter.convert(arg.headValue, ConvertOpts.Empty)
      case Arity.Variable =>
        param.converter.convert(arg.values, ConvertOpts.Empty)
      case Arity.Zero => !!!
    }

    val field: Field = param.reflectInfo.field
    field.setAccessible(true)
    field.set(cmdInstance, convertedValue)
  }

} 
开发者ID:ovunccetin,项目名称:quicli,代码行数:61,代码来源:DefaultCommandLineExecutor.scala


示例20: IllegalCommandClassException

//设置package包名称以及导入依赖的类
package org.quicli.extractors

import java.lang.reflect.{Field, Method}

import org.quicli.QuicliException
import org.quicli.model.Args


class IllegalCommandClassException private(message: String, cause: Throwable = null)
  extends QuicliException(message, cause)

object IllegalCommandClassException {
  def throwAbstractClass(c: Class[_]): Nothing = {
    throwIt(s"Abstract classes or interfaces can not be command types: ${c.getSimpleName}")
  }

  def throwMissingAnnotation(c: Class[_]): Nothing = {
    throwIt(s"@command is missing on ${c.getSimpleName}")
  }

  def throwCommandObject(c: Class[_]): Nothing = {
    throwIt(s"Scala objects cannot be commands: ${c.getSimpleName}")
  }

  def throwMissingConstructor(c: Class[_]): Nothing = {
    throwIt(s"Public no-arg constructor is missing in ${c.getSimpleName}")
  }

  def throwMissingExecMethod(c: Class[_]): Nothing = {
    throwIt(s"Command execution method is missing in ${c.getSimpleName}")
  }

  def throwMultipleExecMethods(c: Class[_], methods: Seq[Method]): Nothing = {
    val methodNames: Seq[String] = methods.map { m =>
      val paramTypes: String = m.getParameterTypes.map(_.getSimpleName).mkString(", ")
      s"${m.getName}($paramTypes)"
    }

    val methodsStr: String = s"${methodNames.init.mkString(", ")} and ${methodNames.last}"

    throwIt(s"Multiple execution methods in ${c.getSimpleName}: $methodsStr")
  }

  def throwInvalidExecMethod(m: Method): Nothing = {
    val paramTypes: String = m.getParameterTypes.map(_.getSimpleName).mkString(", ")
    val methodSign: String = s"${m.getDeclaringClass.getSimpleName}.${m.getName}($paramTypes)"
    val argsClass: String = classOf[Args].getName

    throwIt(s"$methodSign is not a valid execution method! " +
      s"It can be either parameterless or can only take a parameter of type $argsClass.")
  }

  def throwMultipleDefaultParamFields(c: Class[_], fields: Iterable[Field]): Nothing = {
    val fieldNames: String = fields.map(_.getName).mkString(", ")
    throwIt(s"More than one default (nameless) parameters in ${c.getSimpleName}: $fieldNames")
  }

  private def throwIt(message: String, cause: Throwable = null): Nothing = {
    throw new IllegalCommandClassException(message, cause)
  }
} 
开发者ID:ovunccetin,项目名称:quicli,代码行数:62,代码来源:IllegalCommandClassException.scala



注:本文中的java.lang.reflect.Method类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala TaskContext类代码示例发布时间:2022-05-23
下一篇:
Scala Mockito类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap