本文整理汇总了Scala中scala.reflect.ClassTag类的典型用法代码示例。如果您正苦于以下问题:Scala ClassTag类的具体用法?Scala ClassTag怎么用?Scala ClassTag使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ClassTag类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ConditionalStep
//设置package包名称以及导入依赖的类
package com.pacbio.simulator.steps
import com.pacbio.simulator.Scenario
import com.pacbio.simulator.StepResult._
import scala.concurrent.Future
import scala.reflect.{ClassTag, classTag}
trait ConditionalSteps {
this: Scenario with VarSteps =>
implicit class ConditionalStep(s: Step) {
def IF (cond: Var[Boolean]): Step = IfStep(cond, s)
def SHOULD_FAIL: Step = ExpectFailStep(s)
def SHOULD_RAISE[T <: Throwable: ClassTag](clazz: Class[T]): Step = ExpectErrorStep[T](s, clazz)
}
case class IfStep[T](v: Var[Boolean], step: Step) extends Step {
override val name = s"Conditional-${step.name}"
override def run: Future[Result] = if (v.get) step.run else Future { SUPPRESSED }
}
case class ExpectFailStep(step: Step) extends Step {
override val name = s"ExpectFail-${step.name}"
override def run: Future[Result] = step.run.map {
case FAILED(_, _) => SUCCEEDED
case r => FAILED(s"Expected FAILED result but was $r")
}
}
case class ExpectErrorStep[T <: Throwable: ClassTag](step: Step, clazz: Class[T]) extends Step {
override val name = s"ExpectError-${step.name}"
override def run: Future[Result] = step.run.map { r =>
FAILED(s"Expected EXCEPTION result but was $r")
}.recoverWith {
case ex if classTag[T].runtimeClass.isInstance(ex) => Future { SUCCEEDED }
}
}
def fail(failMsg: String): Step = FailStep(failMsg)
case class FailStep[T](failMsg: String) extends Step {
override val name = "Fail"
override def run: Future[Result] = Future { FAILED(failMsg) }
}
def exception(ex: Exception): Step = ExceptionStep(ex)
case class ExceptionStep(ex: Exception) extends Step {
override val name = "Exception"
override def run: Future[Result] = Future { throw ex }
}
}
示例2: LazyLogger
//设置package包名称以及导入依赖的类
package base
import org.slf4j.{ Logger ? SLF4JLogger }
trait LazyLoggerSupport {
val logger = LazyLogger(this.getClass)
}
class LazyLogger(val underlying: SLF4JLogger) {
@inline final def isTraceEnabled = underlying.isTraceEnabled
@inline final def trace(msg: ? String): Unit = if (isTraceEnabled) underlying.trace(msg.toString)
@inline final def trace(msg: ? String, t: ? Throwable): Unit = if (isTraceEnabled) underlying.trace(msg, t)
@inline final def isDebugEnabled = underlying.isDebugEnabled
@inline final def debug(msg: ? String): Unit = if (isDebugEnabled) underlying.debug(msg.toString)
@inline final def debug(msg: ? String, t: ? Throwable): Unit = if (isDebugEnabled) underlying.debug(msg, t)
@inline final def isErrorEnabled = underlying.isErrorEnabled
@inline final def error(msg: ? String): Unit = if (isErrorEnabled) underlying.error(msg.toString)
@inline final def error(msg: ? String, t: ? Throwable): Unit = if (isErrorEnabled) underlying.error(msg, t)
@inline final def isInfoEnabled = underlying.isInfoEnabled
@inline final def info(msg: ? String): Unit = if (isInfoEnabled) underlying.info(msg.toString)
@inline final def info(msg: ? String, t: ? Throwable): Unit = if (isInfoEnabled) underlying.info(msg, t)
@inline final def isWarnEnabled = underlying.isWarnEnabled
@inline final def warn(msg: ? String): Unit = if (isWarnEnabled) underlying.warn(msg.toString)
@inline final def warn(msg: ? String, t: ? Throwable): Unit = if (isWarnEnabled) underlying.warn(msg, t)
}
object LazyLogger {
import scala.reflect.{ classTag, ClassTag }
def apply(name: String): LazyLogger = new LazyLogger(org.slf4j.LoggerFactory.getLogger(name))
def apply(cls: Class[_]): LazyLogger = apply(cls.getName)
def apply[C: ClassTag](): LazyLogger = apply(classTag[C].runtimeClass.getName)
}
示例3: Tag
//设置package包名称以及导入依赖的类
package controllers.api.auth
import com.github.sample.utils.Loggable
import jp.t2v.lab.play2.auth._
import play.api.mvc.Results.Forbidden
import play.api.mvc.{RequestHeader, Result, Results}
import scala.collection.mutable
import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.{ClassTag, classTag}
trait AuthConfigImpl extends AuthConfig with Loggable{
override type Id = String
override type User = MyUser
override val idTag: ClassTag[Id] = classTag[Id]
override def sessionTimeoutInSeconds: Int = 3600 // 1??
override def resolveUser(id: Id)(implicit context: ExecutionContext): Future[Option[User]] = {
Future.successful(AuthService.userOfId(id))
}
override def loginSucceeded(request: RequestHeader)(implicit context: ExecutionContext): Future[Result] = {
Future.successful(Results.Redirect("/"))
}
override def logoutSucceeded(request: RequestHeader)(implicit context: ExecutionContext): Future[Result] = {
Future.successful(Results.Redirect("/login?logout=true"))
}
override def authenticationFailed(request: RequestHeader)(implicit context: ExecutionContext): Future[Result] = {
if(request.acceptedTypes.map(_.toString()).contains("text/html")){
Future.successful(Results.Redirect("/login?failed=true"))
}else{
Future.successful(Results.Unauthorized("Unauthorized"))
}
}
override def authorizationFailed(request: RequestHeader, user: User, authority: Option[Authority])(implicit context: ExecutionContext): Future[Result] = {
Future.successful(Results.Forbidden("No permission"))
}
override def authorize(user: User, authority: Authority)(implicit context: ExecutionContext): Future[Boolean] = Future.successful {
(user.role, authority) match {
case (Administrator, _) => true // Admin?????Action????????
case (NormalUser, NormalUser) => true // ????NormalUser??Action?NormalUser?????????Action?Admin????????????
case _ => false
}
}
override lazy val idContainer: AsyncIdContainer[Id] = AsyncIdContainer(new SessionHandler[Id](CacheImpl.tokenMap, CacheImpl.tokenMap2))
}
object CacheImpl{
val tokenMap: mutable.Map[String, AuthenticityToken] = mutable.Map()
val tokenMap2: mutable.Map[AuthenticityToken, String] = mutable.Map()
}
示例4: JsonSerde
//设置package包名称以及导入依赖的类
package com.github.aseigneurin.kafka.serialization.scala
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.typesafe.scalalogging.LazyLogging
import scala.reflect.{ClassTag, classTag}
class JsonSerde[T >: Null : ClassTag] extends BaseSerde[T] with LazyLogging {
val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
override def deserialize(topic: String, data: Array[Byte]): T = data match {
case null => null
case _ =>
try {
mapper.readValue(data, classTag[T].runtimeClass.asInstanceOf[Class[T]])
} catch {
case e: Exception =>
val jsonStr = new String(data, "UTF-8")
logger.warn(s"Failed parsing ${jsonStr}", e)
null
}
}
override def serialize(topic: String, obj: T): Array[Byte] = {
mapper.writeValueAsBytes(obj)
}
}
示例5: Tag
//设置package包名称以及导入依赖的类
package config
import controllers.routes
import jp.t2v.lab.play2.auth._
import model.user.access.Role
import model.user.access.Role.{Administrator, BlockedUser, User}
import model.user.dao.UserDAO
import play.api.mvc.Results._
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.{ClassTag, classTag}
trait AuthConfiguration extends AuthConfig {
type Id = Long
type User = model.user.User
type Authority = Role
val userDAO: UserDAO
val idTag: ClassTag[Id] = classTag[Id]
val sessionTimeoutInSeconds: Int = 3600
def resolveUser(id: Id)(implicit ctx: ExecutionContext): Future[Option[User]] = userDAO.get(id)
def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] = {
val uri = request.session.get("access_uri").getOrElse(routes.Tasks.getTaskPage().url.toString)
Future.successful(Redirect(uri).withSession(request.session - "access_uri"))
}
def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] =
Future.successful(Redirect(routes.Tasks.getTaskPage()))
def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext): Future[Result] =
Future.successful(Redirect(controllers.auth.routes.AuthController.login()).withSession("access_uri" -> request.uri))
override def authorizationFailed(request: RequestHeader, user: User, authority: Option[Authority])(implicit context: ExecutionContext): Future[Result] = {
Future.successful(Forbidden("no permission"))
}
def authorize(user: User, authority: Authority)(implicit ctx: ExecutionContext): Future[Boolean] = Future.successful {
(user.role, authority) match {
case ( Administrator, _ ) => true
case ( User, User ) => true
case ( BlockedUser, BlockedUser ) => true
case _ => false
}
}
override lazy val tokenAccessor = new CookieTokenAccessor(
cookieSecureOption = play.api.Play.isProd(play.api.Play.current),
cookieMaxAge = Some(sessionTimeoutInSeconds)
)
}
示例6: TypeUtilsTest
//设置package包名称以及导入依赖的类
package scalera.ddd.utils
import scala.reflect.classTag
import org.scalatest.{FlatSpec, Matchers}
class TypeUtilsTest extends FlatSpec with Matchers {
behavior of "TypeUtils"
import TypeUtils._
class Kid
class Daddy extends Kid
class Grandpa extends Daddy
it should "determine if a type inherits from some other" in {
classTag[Kid].isA[Kid] should equal(true)
classTag[Kid].isA[Daddy] should equal(false)
classTag[Daddy].isA[Grandpa] should equal(false)
classTag[Grandpa].isA[Kid] should equal(true)
}
it should "determine if a type inherits from some other (using class format)" in {
classOf[Kid].isA[Kid] should equal(true)
classOf[Kid].isA[Daddy] should equal(false)
classOf[Daddy].isA[Grandpa] should equal(false)
classOf[Grandpa].isA[Kid] should equal(true)
}
}
示例7: Tag
//设置package包名称以及导入依赖的类
package controllers.basic
import play.api.mvc.RequestHeader
import play.api.mvc.Results._
import scala.concurrent.{Future, ExecutionContext}
import jp.t2v.lab.play2.auth.AuthConfig
import model.{Role, Account}
import model.Role._
import scala.reflect.{ClassTag, classTag}
trait AuthConfigImpl extends AuthConfig {
type Id = Account
type User = Account
type Authority = Role
val idTag: ClassTag[Id] = classTag[Id]
val sessionTimeoutInSeconds = 3600
def resolveUser(id: Id)(implicit ctx: ExecutionContext) = Future.successful(Some(id))
def authorize(user: User, authority: Authority)(implicit ctx: ExecutionContext) = Future.successful((user.role, authority) match {
case (Administrator, _) => true
case (NormalUser, NormalUser) => true
case _ => false
})
def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = throw new AssertionError("don't use application Login")
def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = throw new AssertionError("don't use application Logout")
def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful {
Unauthorized.withHeaders("WWW-Authenticate" -> """Basic realm="SECRET AREA"""")
}
def authorizationFailed(request: RequestHeader, user: User, authority: Option[Authority])(implicit ctx: ExecutionContext) = Future.successful(Forbidden("no permission"))
override lazy val idContainer = new BasicAuthIdContainer
override lazy val tokenAccessor = new BasicAuthTokenAccessor
}
示例8: Tag
//设置package包名称以及导入依赖的类
package controllers.api.auth
import com.github.uryyyyyyy.utils.Loggable
import jp.t2v.lab.play2.auth._
import play.api.mvc.Results.Forbidden
import play.api.mvc.{RequestHeader, Result, Results}
import scala.collection.mutable
import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.{ClassTag, classTag}
trait AuthConfigImpl extends AuthConfig with Loggable{
override type Id = String
override type User = MyUser
override val idTag: ClassTag[Id] = classTag[Id]
override def sessionTimeoutInSeconds: Int = 3600 // 1??
override def resolveUser(id: Id)(implicit context: ExecutionContext): Future[Option[User]] = {
Future.successful(AuthService.userOfId(id))
}
override def loginSucceeded(request: RequestHeader)(implicit context: ExecutionContext): Future[Result] = {
Future.successful(Results.Redirect("/"))
}
override def logoutSucceeded(request: RequestHeader)(implicit context: ExecutionContext): Future[Result] = {
Future.successful(Results.Redirect("/login?logout=true"))
}
override def authenticationFailed(request: RequestHeader)(implicit context: ExecutionContext): Future[Result] = {
if(request.acceptedTypes.map(_.toString()).contains("text/html")){
Future.successful(Results.Redirect("/login?failed=true"))
}else{
Future.successful(Results.Unauthorized("Unauthorized"))
}
}
override def authorizationFailed(request: RequestHeader, user: User, authority: Option[Authority])(implicit context: ExecutionContext): Future[Result] = {
Future.successful(Results.Forbidden("No permission"))
}
override def authorize(user: User, authority: Authority)(implicit context: ExecutionContext): Future[Boolean] = Future.successful {
(user.role, authority) match {
case (Administrator, _) => true // Admin?????Action????????
case (NormalUser, NormalUser) => true // ????NormalUser??Action?NormalUser?????????Action?Admin????????????
case _ => false
}
}
override lazy val idContainer: AsyncIdContainer[Id] = AsyncIdContainer(new SessionHandler[Id](CacheImpl.tokenMap, CacheImpl.tokenMap2))
}
object CacheImpl{
val tokenMap: mutable.Map[String, AuthenticityToken] = mutable.Map()
val tokenMap2: mutable.Map[AuthenticityToken, String] = mutable.Map()
}
示例9: LazyLogger
//设置package包名称以及导入依赖的类
package com.avsystem.scex
package util
import org.slf4j.{Logger, LoggerFactory}
import scala.reflect.{ClassTag, classTag}
trait LoggingUtils {
protected case class LazyLogger(underlying: Logger) {
def trace(msg: => String, cause: Throwable = null): Unit = {
if (underlying.isTraceEnabled) {
underlying.trace(msg, cause)
}
}
def debug(msg: => String, cause: Throwable = null): Unit = {
if (underlying.isDebugEnabled) {
underlying.debug(msg, cause)
}
}
def info(msg: => String, cause: Throwable = null): Unit = {
if (underlying.isInfoEnabled) {
underlying.info(msg, cause)
}
}
def warn(msg: => String, cause: Throwable = null): Unit = {
if (underlying.isWarnEnabled) {
underlying.warn(msg, cause)
}
}
def error(msg: => String, cause: Throwable = null): Unit = {
if (underlying.isErrorEnabled) {
underlying.error(msg, cause)
}
}
}
protected def createLogger[T: ClassTag] =
LazyLogger(LoggerFactory.getLogger(classTag[T].runtimeClass))
}
示例10: ClassTags
//设置package包名称以及导入依赖的类
package shark.api
import scala.reflect.classTag
object ClassTags {
// List of primitive ClassTags.
val jBoolean = classTag[java.lang.Boolean]
val jByte = classTag[java.lang.Byte]
val jShort = classTag[java.lang.Short]
val jInt = classTag[java.lang.Integer]
val jLong = classTag[java.lang.Long]
val jFloat = classTag[java.lang.Float]
val jDouble = classTag[java.lang.Double]
}
示例11: InMemoryRegistry
//设置package包名称以及导入依赖的类
package io.corbel.functions.registry.memory
import grizzled.slf4j.Logging
import io.corbel.functions.model.{Activator, CorbelFunction}
import io.corbel.functions.registry.{Registry, RegistryFindCriteria}
import scala.reflect.{ClassTag, classTag}
class InMemoryRegistry extends Registry with Logging {
var functions = Vector.empty[CorbelFunction]
override def find[T <: CorbelFunction : ClassTag](criteria: RegistryFindCriteria[_ >: T]): Seq[T] = {
val `type` = classTag[T].runtimeClass
debug(s"Searching registry for ${`type`} with criteria: $criteria. Registry size = ${functions.size}")
functions.flatMap({
case e: T => Some(e)
case _ => None
})
}
override def register(f: CorbelFunction, activators: Activator*): Unit = {
debug(s"Registering function: $f")
functions +:= f
}
}
示例12: Tag
//设置package包名称以及导入依赖的类
package controllers.security
import jp.t2v.lab.play2.auth.AuthConfig
import models.Role.{Administrator, NormalUser}
import models.{Account, Role}
import play.api.mvc.RequestHeader
import play.api.mvc.Results._
import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.{ClassTag, classTag}
trait AuthConfigImpl extends AuthConfig {
type Id = Account
type User = Account
type Authority = Role
val idTag: ClassTag[Id] = classTag[Id]
val sessionTimeoutInSeconds = 3600
def resolveUser(id: Id)(implicit ctx: ExecutionContext) = Future.successful(Some(id))
def authorize(user: User, authority: Authority)(implicit ctx: ExecutionContext) = Future.successful((Role.valueOf(user.role), authority) match {
case (Administrator, _) => true
case (NormalUser, NormalUser) => true
case _ => false
})
def loginSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = throw new AssertionError("don't use application Login")
def logoutSucceeded(request: RequestHeader)(implicit ctx: ExecutionContext) = throw new AssertionError("don't use application Logout")
def authenticationFailed(request: RequestHeader)(implicit ctx: ExecutionContext) = Future.successful {
Unauthorized.withHeaders("WWW-Authenticate" -> """Basic realm="SECRET AREA"""")
}
def authorizationFailed(request: RequestHeader, user: User, authority: Option[Authority])(implicit ctx: ExecutionContext) = Future.successful(Forbidden("no permission"))
override lazy val idContainer = new BasicAuthIdContainer
override lazy val tokenAccessor = new BasicAuthTokenAccessor
}
示例13: Utils
//设置package包名称以及导入依赖的类
package utils
import scala.reflect.runtime.universe.{ Type, typeTag, _ }
import scala.reflect.{ ClassTag, ManifestFactory, classTag }
object Utils {
def classTag2Manifest[T: ClassTag]: Manifest[T] = {
val clazz = classTag[T].runtimeClass
ManifestFactory.classType(clazz).asInstanceOf[Manifest[T]]
}
def typeTag2Manifest[T: TypeTag]: Manifest[T] = {
val t = typeTag[T]
val mirror = t.mirror
def toManifestRec(t: Type): Manifest[_] = {
val clazz = ClassTag[T](mirror.runtimeClass(t)).runtimeClass
if (t.typeArgs.length == 1) {
val arg = toManifestRec(t.typeArgs.head)
ManifestFactory.classType(clazz, arg)
} else if (t.typeArgs.length > 1) {
val args = t.typeArgs.map(x => toManifestRec(x))
ManifestFactory.classType(clazz, args.head, args.tail: _*)
} else {
ManifestFactory.classType(clazz)
}
}
toManifestRec(t.tpe).asInstanceOf[Manifest[T]]
}
implicit class SafeGetOrElse[T](val o: Option[T]) {
def safeGetOrElse(or: T): T = o match {
case Some(v) => v
case None => or
}
}
}