本文整理汇总了Scala中java.lang.reflect.Type类的典型用法代码示例。如果您正苦于以下问题:Scala Type类的具体用法?Scala Type怎么用?Scala Type使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Type类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: JSONHTTP
//设置package包名称以及导入依赖的类
package works.weave.socks.aws.orders.dataaccess.web
import com.amazonaws.util.IOUtils
import com.fasterxml.jackson.core.`type`.TypeReference
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.net.URI
import javax.xml.ws.http.HTTPException
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClientBuilder
import org.slf4j.LoggerFactory
import works.weave.socks.aws.orders.ProjectDefaultJacksonMapper
object JSONHTTP {
val Log = LoggerFactory.getLogger(getClass)
val objectMapper = ProjectDefaultJacksonMapper.build() // after (_.bla)
def get[T : Manifest : NotNothing](uri : URI) : T = {
val client = HttpClientBuilder.create.build
val get = new HttpGet(uri)
get.addHeader("Accept", "application/json")
val response = client.execute(get)
val responseString = IOUtils.toString(response.getEntity.getContent)
Log.info(s"Got status ${response.getStatusLine.getStatusCode}")
if (response.getStatusLine.getStatusCode == 200) {
Log.info(s"Got response from URI $uri: $responseString")
objectMapper.readValue(responseString, typeReference[T])
} else {
throw new HTTPException(response.getStatusLine.getStatusCode)
}
}
def typeReference[T : Manifest] = new TypeReference[T] {
override def getType = typeFromManifest(manifest[T])
}
def typeFromManifest(m : Manifest[_]) : Type = {
if (m.typeArguments.isEmpty) { m.runtimeClass }
else new ParameterizedType {
def getRawType = m.runtimeClass
def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray
def getOwnerType = null
}
}
// Trick to disable nothign for type param
sealed trait NotNothing[-T]
object NotNothing {
implicit object notNothing extends NotNothing[Any]
implicit object `The error is because the missing type parameter was resolved to Nothing` extends NotNothing[Nothing]
}
}
开发者ID:Compositional,项目名称:orders-aws,代码行数:57,代码来源:JSONHTTP.scala
示例2: PersistentActorMessage
//设置package包名称以及导入依赖的类
package info.unterstein.akka.persistence.api
import com.google.gson._
import java.lang.reflect.Type
import com.google.gson.reflect.TypeToken
import org.slf4j.LoggerFactory
import scala.collection.JavaConverters._
case class PersistentActorMessage(messageType: String, scheduleDate: Long, originalMessage: Map[String, String])
object PersistentActorMessage {
private val mapToken = new TypeToken[java.util.Map[String, String]](){}.getType
private val log = LoggerFactory.getLogger(PersistentActorMessage.getClass)
private val gson = new GsonBuilder()
.registerTypeAdapter(classOf[Map[String, String]], new MapSerializer())
.create()
private class MapSerializer extends JsonSerializer[Map[String, String]] with JsonDeserializer[Map[String, String]] {
override def serialize(src: Map[String, String], typeOfSrc: Type, context: JsonSerializationContext): JsonElement = {
gson.toJsonTree(src.asJava)
}
override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Map[String, String] = {
val result: java.util.Map[String, String] = gson.fromJson(json, mapToken)
result.asScala.toMap
}
}
def jsonToMap(json: String): Map[String, String] = {
try {
val result: java.util.Map[String, String] = gson.fromJson(json, mapToken)
result.asScala.toMap
} catch {
case o_O: Exception =>
log.error("Deserialization failed for " + json, o_O)
throw new RuntimeException("Deserialization failed!", o_O)
}
}
def mapToJson(map: Map[String, String]): String = gson.toJson(map.asJava)
}
开发者ID:unterstein,项目名称:persistent-actor-messages,代码行数:49,代码来源:PersistentActorMessage.scala
示例3: JacksonSupport
//设置package包名称以及导入依赖的类
package com.github.andyglow.relaxed
import com.fasterxml.jackson.core.`type`.TypeReference
import com.fasterxml.jackson.databind._
case class JacksonSupport(json: JsonNode) extends Reader with ReaderSupport[JsonNode] {
def isNull: (JsonNode) => Boolean = _.isNull
def ctor: (JsonNode) => JacksonSupport = JacksonSupport.apply
def get(field: String): Option[JsonNode] = {
val node = json.findPath(field)
if (node.isMissingNode) None else Some(node)
}
override def opt[T: Reads](field: String): Option[T] = {
val r = implicitly[Reads[T]].asInstanceOf[JacksonSupport.JacksonReads[T]]
get(field) map {x => r.mapper.readerFor(r.typeReference).readValue[T](x)}
}
override def optOpt[T: Reads](field: String): Option[Option[T]] = {
val r = implicitly[Reads[T]].asInstanceOf[JacksonSupport.JacksonReads[T]]
getOpt(field) map {_ map {x => r.mapper.readerFor(r.typeReference).readValue[T](x)}}
}
}
object JacksonSupport {
import java.lang.reflect.{Type, ParameterizedType}
sealed trait JacksonReads[T] extends Reads[T] {
def mapper: ObjectMapper
def typeReference: TypeReference[T]
}
implicit def readsImpl[T](implicit x: ObjectMapper, m: Manifest[T]): Reads[T] = new JacksonReads[T]() {
override def mapper: ObjectMapper = x
override lazy val typeReference: TypeReference[T] = {
def typeFromManifest(m: Manifest[_]): Type = {
if (m.typeArguments.isEmpty) m.runtimeClass
else new ParameterizedType {
def getRawType: Class[_] = m.runtimeClass
def getActualTypeArguments: Array[Type] = m.typeArguments.map(typeFromManifest).toArray
def getOwnerType = null
}
}
new TypeReference[T] {
override def getType: Type = typeFromManifest(manifest[T])
}
}
}
}
开发者ID:andyglow,项目名称:relaxed-json-update,代码行数:51,代码来源:JacksonSupport.scala
示例4: FieldModel
//设置package包名称以及导入依赖的类
package io.skysail.core.model
import java.lang.reflect.Field
import java.lang.reflect.Type
import java.util.Collection
import io.skysail.core.restlet.utils.ScalaReflectionUtils
case class FieldModel(val f: java.lang.reflect.Field) {
require(f != null, "you must provide a non-null field to construct a FieldModel")
val name = f.getName
//def getInputType(): String = f.getAnnotation(classOf[io.skysail.core.html.Field]).inputType().name();
def isMandatory(): Boolean = {
val notNullAnnotation = f.getAnnotation(classOf[javax.validation.constraints.NotNull]);
if (notNullAnnotation != null) {
return true;
}
val sizeAnnotation = f.getAnnotation(classOf[javax.validation.constraints.Size]);
if (sizeAnnotation != null) {
if (sizeAnnotation.min() > 0) {
return true;
}
}
return false;
}
//override def toString() = s"""${this.getClass.getSimpleName}(inputType: $getInputType, mandatory: $isMandatory)"""
private def getEntityType() = {
if (classOf[Collection[_]].isAssignableFrom(f.getType()))
ScalaReflectionUtils.getParameterizedType(f);
else
null
}
}
开发者ID:evandor,项目名称:skysail-core,代码行数:39,代码来源:FieldModel.scala
示例5: CatalogTypeDeSerializer
//设置package包名称以及导入依赖的类
package de.randombyte.nightmare_ai.config
import java.lang.reflect.Type
import java.util.function.Supplier
import com.google.gson._
import org.spongepowered.api.{CatalogType, GameRegistry}
class CatalogTypeDeSerializer[T <: CatalogType](registry: GameRegistry, classOfT: Class[T])
extends JsonDeserializer[T] with JsonSerializer[T] {
override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): T = {
registry.getType[T](classOfT, json.getAsString).orElseThrow(new Supplier[JsonParseException] {
override def get(): JsonParseException =
new JsonParseException(s"Couldn't find '${json.getAsString}' in GameRegistry")
})
}
override def serialize(catalogType: T, typeOfSrc: Type, context: JsonSerializationContext): JsonElement =
new JsonPrimitive(catalogType.getId)
}
开发者ID:randombyte-developer,项目名称:NightmareAI,代码行数:22,代码来源:CatalogTypeDeSerializer.scala
示例6: serialize
//设置package包名称以及导入依赖的类
package com.lightbend.lagom.internal.javadsl.api
import java.lang.reflect.{ ParameterizedType, Type }
import java.util.Optional
import com.lightbend.lagom.javadsl.api.deser.{ PathParamSerializer, PathParamSerializers }
import org.pcollections.{ PSequence, TreePVector }
import scala.compat.java8.FunctionConverters._
trait UnresolvedPathParamSerializer[Param] extends PathParamSerializer[Param] {
def serialize(parameter: Param) = throw new NotImplementedError("Cannot use unresolved path param serializer to serialize path params")
def deserialize(parameters: PSequence[String]) = throw new NotImplementedError("Cannot use unresolved path param serializer to deserialize path params")
def resolve(resolver: ServiceCallResolver, typeInfo: Type): PathParamSerializer[Param]
}
class UnresolvedTypePathParamSerializer[Param] extends UnresolvedPathParamSerializer[Param] {
override def resolve(resolver: ServiceCallResolver, typeInfo: Type): PathParamSerializer[Param] = {
resolver.pathParamSerializerFor(typeInfo, typeInfo)
}
}
class UnresolvedOptionalPathParamSerializer[Param] extends UnresolvedPathParamSerializer[Optional[Param]] {
override def resolve(resolver: ServiceCallResolver, typeInfo: Type): PathParamSerializer[Optional[Param]] = {
typeInfo match {
case paramType: ParameterizedType if paramType.getRawType == classOf[Optional[_]] =>
val wrappedType = paramType.getActualTypeArguments.apply(0)
val subTypeSerializer = resolver.pathParamSerializerFor[Param](wrappedType, wrappedType)
PathParamSerializers.optional[Param](
wrappedType.getTypeName,
(subTypeSerializer.deserialize _).compose((p: String) => TreePVector.singleton(p)).asJava,
(subTypeSerializer.serialize _).andThen {
case single if single.size() == 1 => single.get(0)
case other => throw new IllegalStateException("Can only wrap an Optional serializer around a path param serializer that produces exactly one parameter")
}.asJava
)
case _ => throw new IllegalArgumentException("Unresolved optional path param serializer can only be resolved against ParamaterizedType descriptors for the Optional class. This serializer was resolved against: " + typeInfo)
}
}
}
开发者ID:lagom,项目名称:lagom,代码行数:43,代码来源:PathParamSerializers.scala
示例7: EitherTypeModifier
//设置package包名称以及导入依赖的类
package com.kakao.shaded.jackson.module.scala.modifiers
import java.lang.reflect.Type
import com.kakao.shaded.jackson.databind.JavaType
import com.kakao.shaded.jackson.databind.`type`.{ReferenceType, TypeFactory, TypeBindings, TypeModifier}
import com.kakao.shaded.jackson.module.scala.JacksonModule
private object EitherTypeModifier extends TypeModifier with GenTypeModifier {
val EITHER = classOf[Either[AnyRef, AnyRef]]
override def modifyType(typ: JavaType, jdkType: Type, context: TypeBindings, typeFactory: TypeFactory): JavaType = {
if (typ.isReferenceType || typ.isContainerType) typ
if (classObjectFor(jdkType).exists(EITHER.isAssignableFrom)) {
ReferenceType.upgradeFrom(typ, typ)
} else typ
}
}
trait EitherTypeModifierModule extends JacksonModule {
this += EitherTypeModifier
}
开发者ID:kakao,项目名称:mango,代码行数:24,代码来源:EitherTypeModifier.scala
示例8: OptionTypeModifier
//设置package包名称以及导入依赖的类
package com.kakao.shaded.jackson.module.scala.modifiers
import java.lang.reflect.Type
import com.kakao.shaded.jackson.databind.JavaType
import com.kakao.shaded.jackson.databind.`type`.{ReferenceType, TypeBindings, TypeFactory, TypeModifier}
import com.kakao.shaded.jackson.module.scala.JacksonModule
private object OptionTypeModifier extends TypeModifier with GenTypeModifier {
val OPTION = classOf[Option[AnyRef]]
override def modifyType(typ: JavaType, jdkType: Type, context: TypeBindings, typeFactory: TypeFactory): JavaType = {
if (typ.isReferenceType || typ.isContainerType) return typ
if (classObjectFor(jdkType).exists(OPTION.isAssignableFrom)) {
ReferenceType.upgradeFrom(typ, typ.containedTypeOrUnknown(0))
} else typ
}
}
trait OptionTypeModifierModule extends JacksonModule {
this += OptionTypeModifier
}
开发者ID:kakao,项目名称:mango,代码行数:24,代码来源:OptionTypeModifierModule.scala
示例9: DurationAsMillisConverter
//设置package包名称以及导入依赖的类
package cz.augi.gsonscala
import java.lang.reflect.Type
import java.time.Duration
import com.google.gson.{JsonDeserializationContext, _}
object DurationAsMillisConverter extends JsonSerializer[Duration] with JsonDeserializer[Duration] {
override def serialize(src: Duration, typeOfSrc: Type, context: JsonSerializationContext): JsonElement = new JsonPrimitive(src.toMillis)
override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Duration = Duration.ofMillis(json.getAsLong)
}
object DurationAsSecondsConverter extends JsonSerializer[Duration] with JsonDeserializer[Duration] {
override def serialize(src: Duration, typeOfSrc: Type, context: JsonSerializationContext): JsonElement = new JsonPrimitive(src.getSeconds)
override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Duration = Duration.ofSeconds(json.getAsLong)
}
object DurationAsStringConverter extends JsonSerializer[Duration] with JsonDeserializer[Duration] {
override def serialize(src: Duration, typeOfSrc: Type, context: JsonSerializationContext): JsonElement = new JsonPrimitive(src.toString)
override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Duration = Duration.parse(json.getAsString)
}
开发者ID:augi,项目名称:gson-scala,代码行数:22,代码来源:DurationConverter.scala
示例10: InstantAsUnixSecondsConverter
//设置package包名称以及导入依赖的类
package cz.augi.gsonscala
import java.lang.reflect.Type
import java.time.Instant
import java.time.format.DateTimeFormatter
import com.google.gson.{JsonDeserializationContext, _}
object InstantAsUnixSecondsConverter extends JsonSerializer[Instant] with JsonDeserializer[Instant] {
def serialize(src: Instant, typeOfSrc: Type, context: JsonSerializationContext): JsonElement = new JsonPrimitive(src.getEpochSecond)
def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Instant = Instant.ofEpochSecond(json.getAsLong)
}
object InstantAsUnixMillisConverter extends JsonSerializer[Instant] with JsonDeserializer[Instant] {
def serialize(src: Instant, typeOfSrc: Type, context: JsonSerializationContext): JsonElement = new JsonPrimitive(src.toEpochMilli)
def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Instant = Instant.ofEpochMilli(json.getAsLong)
}
object InstantAsStringConverter extends JsonSerializer[Instant] with JsonDeserializer[Instant] {
def serialize(src: Instant, typeOfSrc: Type, context: JsonSerializationContext): JsonElement = new JsonPrimitive(DateTimeFormatter.ISO_INSTANT.format(src))
def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Instant = Instant.from(DateTimeFormatter.ISO_INSTANT.parse(json.getAsString))
}
开发者ID:augi,项目名称:gson-scala,代码行数:23,代码来源:InstantConverter.scala
示例11: ScalaDurationAsMillisConverter
//设置package包名称以及导入依赖的类
package cz.augi.gsonscala
import java.lang.reflect.Type
import java.util.concurrent.TimeUnit
import com.google.gson.{JsonDeserializationContext, _}
import scala.concurrent.duration.Duration
object ScalaDurationAsMillisConverter extends JsonSerializer[Duration] with JsonDeserializer[Duration] {
override def serialize(src: Duration, typeOfSrc: Type, context: JsonSerializationContext): JsonElement = new JsonPrimitive(src.toMillis)
override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Duration = Duration(json.getAsLong, TimeUnit.MILLISECONDS)
}
object ScalaDurationAsSecondsConverter extends JsonSerializer[Duration] with JsonDeserializer[Duration] {
override def serialize(src: Duration, typeOfSrc: Type, context: JsonSerializationContext): JsonElement = new JsonPrimitive(src.toSeconds)
override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Duration = Duration(json.getAsLong, TimeUnit.SECONDS)
}
object ScalaDurationAsStringConverter extends JsonSerializer[Duration] with JsonDeserializer[Duration] {
override def serialize(src: Duration, typeOfSrc: Type, context: JsonSerializationContext): JsonElement = new JsonPrimitive(src.toString)
override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Duration = Duration(json.getAsString)
}
开发者ID:augi,项目名称:gson-scala,代码行数:24,代码来源:ScalaDurationConverter.scala
注:本文中的java.lang.reflect.Type类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论