本文整理汇总了Scala中java.lang.reflect.Method类的典型用法代码示例。如果您正苦于以下问题:Scala Method类的具体用法?Scala Method怎么用?Scala Method使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Method类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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();
}
}
}
}
示例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:_*)
}
}
示例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)
)
}
}
示例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)
}
}
示例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)
}
}
示例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)
}
}
}
示例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)))
}
}
示例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)
}
})
}
}
示例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]])
}
}
示例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
}
}
}
示例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)
}
}
示例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)
}
}
}
}
示例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
}
示例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
}
}
示例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
}
}