java.lang.reflect.Constructor Scala Examples
The following examples show how to use java.lang.reflect.Constructor.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: ExceptionSerializer.scala From reliable-http-client with Apache License 2.0 | 5 votes |
package rhttpc.transport.json4s import java.lang.reflect.Constructor import org.json4s.{CustomSerializer, Extraction, Formats, Serializer, TypeInfo} import org.json4s.JsonAST._ import scala.util.Try object ExceptionSerializer extends Serializer[Throwable] { override def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Throwable] = { case ( TypeInfo(clazz, _), JObject(("jsonClass", JString(ExceptionClassHavingConstructorWithMessageAndCause(constructor))) :: ("message", JString(message)) :: ("cause", cause) :: Nil)) if classOf[Throwable].isAssignableFrom(clazz) => constructor.newInstance(message, Extraction.extract[Throwable](cause)) case ( TypeInfo(clazz, _), JObject(("jsonClass", JString(ExceptionClassHavingConstructorWithMessageAndCause(constructor))) :: ("message", JNull) :: ("cause", cause) :: Nil)) if classOf[Throwable].isAssignableFrom(clazz) => constructor.newInstance(null, Extraction.extract[Throwable](cause)) case ( TypeInfo(clazz, _), JObject(("jsonClass", JString(ExceptionClassHavingConstructorWithMessageOnly(constructor))) :: ("message", JString(message)) :: Nil)) if classOf[Throwable].isAssignableFrom(clazz) => constructor.newInstance(message) case ( TypeInfo(clazz, _), JObject(("jsonClass", JString(ExceptionClassHavingConstructorWithMessageOnly(constructor))) :: ("message", JNull) :: Nil)) if classOf[Throwable].isAssignableFrom(clazz) => constructor.newInstance(null) } override def serialize(implicit formats: Formats): PartialFunction[Any, JValue] = { case ExceptionInstanceHavingConstructorWithMessageAndCause(ex) => JObject( formats.typeHintFieldName -> JString(ex.getClass.getName), "message" -> Option(ex.getMessage).map(JString).getOrElse(JNull), "cause" -> Extraction.decompose(ex.getCause) ) case ExceptionInstanceHavingConstructorWithMessageOnly(ex) => JObject( formats.typeHintFieldName -> JString(ex.getClass.getName), "message" -> Option(ex.getMessage).map(JString).getOrElse(JNull) ) } } object ExceptionClassHavingConstructorWithMessageAndCause { def unapply(className: String): Option[Constructor[Throwable]] = { (for { clazz <- Try(Class.forName(className)) if classOf[Throwable].isAssignableFrom(clazz) constructor <- constructorWithMessageAndCause(clazz) } yield constructor).toOption } def constructorWithMessageAndCause(clazz: Class[_]): Try[Constructor[Throwable]] = Try(clazz.getDeclaredConstructor(classOf[String], classOf[Throwable]).asInstanceOf[Constructor[Throwable]]) } object ExceptionInstanceHavingConstructorWithMessageAndCause { def unapply(instance: Throwable): Option[Throwable] = { ExceptionClassHavingConstructorWithMessageAndCause.constructorWithMessageAndCause(instance.getClass).map(_ => instance).toOption } } object ExceptionClassHavingConstructorWithMessageOnly { def unapply(className: String): Option[Constructor[Throwable]] = { (for { clazz <- Try(Class.forName(className)) if classOf[Throwable].isAssignableFrom(clazz) constructor <- constructorWithMessageOnly(clazz) } yield constructor).toOption } def constructorWithMessageOnly(clazz: Class[_]): Try[Constructor[Throwable]] = Try(clazz.getDeclaredConstructor(classOf[String]).asInstanceOf[Constructor[Throwable]]) } object ExceptionInstanceHavingConstructorWithMessageOnly { def unapply(instance: Throwable): Option[Throwable] = { ExceptionClassHavingConstructorWithMessageOnly.constructorWithMessageOnly(instance.getClass).map(_ => instance).toOption } }
Example 2
Source File: PropertyDescriptor.scala From mango with Apache License 2.0 | 5 votes |
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 } }
Example 3
Source File: Accessible.scala From mango with Apache License 2.0 | 5 votes |
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 } }
Example 4
Source File: DefaultParameters.scala From mango with Apache License 2.0 | 5 votes |
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 } }
Example 5
Source File: ScalaDefaultValuesInjector.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package spring import java.lang.reflect.{Constructor, Method, Modifier} import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder import org.springframework.beans.factory.config.{BeanDefinition, BeanDefinitionHolder, ConfigurableListableBeanFactory} import org.springframework.beans.factory.support.{BeanDefinitionRegistry, BeanDefinitionRegistryPostProcessor, ManagedList, ManagedMap, ManagedSet} import org.springframework.core.ParameterNameDiscoverer import scala.beans.BeanProperty import scala.reflect.{ScalaLongSignature, ScalaSignature} class ScalaDefaultValuesInjector extends BeanDefinitionRegistryPostProcessor { @BeanProperty var paramNameDiscoverer: ParameterNameDiscoverer = new ScalaParameterNameDiscoverer def classLoader: ClassLoader = Thread.currentThread.getContextClassLoader.opt getOrElse getClass.getClassLoader def loadClass(name: String): Class[_] = Class.forName(name, false, classLoader) def postProcessBeanDefinitionRegistry(registry: BeanDefinitionRegistry): Unit = { def traverse(value: Any): Unit = value match { case bd: BeanDefinition => bd.getConstructorArgumentValues.getGenericArgumentValues.asScala.foreach(traverse) bd.getConstructorArgumentValues.getIndexedArgumentValues.values.asScala.foreach(traverse) bd.getPropertyValues.getPropertyValueList.asScala.foreach(pv => traverse(pv.getValue)) injectDefaultValues(bd) case bdw: BeanDefinitionHolder => traverse(bdw.getBeanDefinition) case vh: ValueHolder => traverse(vh.getValue) case ml: ManagedList[_] => ml.asScala.foreach(traverse) case ms: ManagedSet[_] => ms.asScala.foreach(traverse) case mm: ManagedMap[_, _] => mm.asScala.foreach { case (k, v) => traverse(k) traverse(v) } case _ => } registry.getBeanDefinitionNames .foreach(n => traverse(registry.getBeanDefinition(n))) } private def isScalaClass(cls: Class[_]): Boolean = cls.getEnclosingClass match { case null => cls.getAnnotation(classOf[ScalaSignature]) != null || cls.getAnnotation(classOf[ScalaLongSignature]) != null case encls => isScalaClass(encls) } private def injectDefaultValues(bd: BeanDefinition): Unit = bd.getBeanClassName.opt.map(loadClass) .recoverToOpt[ClassNotFoundException].flatten.filter(isScalaClass) .foreach { clazz => val usingConstructor = bd.getFactoryMethodName == null val factoryExecs = if (usingConstructor) clazz.getConstructors.toVector else clazz.getMethods.iterator.filter(_.getName == bd.getFactoryMethodName).toVector val factorySymbolName = if (usingConstructor) "$lessinit$greater" else bd.getFactoryMethodName if (factoryExecs.size == 1) { val constrVals = bd.getConstructorArgumentValues val factoryExec = factoryExecs.head val paramNames = factoryExec match { case c: Constructor[_] => paramNameDiscoverer.getParameterNames(c) case m: Method => paramNameDiscoverer.getParameterNames(m) } (0 until factoryExec.getParameterCount).foreach { i => def defaultValueMethod = clazz.getMethod(s"$factorySymbolName$$default$$${i + 1}") .recoverToOpt[NoSuchMethodException].filter(m => Modifier.isStatic(m.getModifiers)) def specifiedNamed = paramNames != null && constrVals.getGenericArgumentValues.asScala.exists(_.getName == paramNames(i)) def specifiedIndexed = constrVals.getIndexedArgumentValues.get(i) != null if (!specifiedNamed && !specifiedIndexed) { defaultValueMethod.foreach { dvm => constrVals.addIndexedArgumentValue(i, dvm.invoke(null)) } } } } } def postProcessBeanFactory(beanFactory: ConfigurableListableBeanFactory): Unit = () }
Example 6
Source File: ScalaParameterNameDiscoverer.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package spring import java.lang.reflect.{Constructor, Executable, Method, Modifier} import com.github.ghik.silencer.silent import org.springframework.core.{JdkVersion, ParameterNameDiscoverer} import scala.annotation.tailrec import scala.ref.WeakReference import scala.reflect.api.JavaUniverse import scala.reflect.{ScalaLongSignature, ScalaSignature} object ScalaParameterNameDiscoverer { final val ScalaSignatureClasses = List(classOf[ScalaSignature], classOf[ScalaLongSignature]) @silent("deprecated") final val JdkAtLeast8 = JdkVersion.getMajorJavaVersion >= JdkVersion.JAVA_18 // we don't want to keep the universe in memory forever, so we don't use scala.reflect.runtime.universe private var universeRef: WeakReference[JavaUniverse] = _ private def universe: JavaUniverse = { universeRef.option.flatMap(_.get) match { case Some(result) => result case None => val result = new scala.reflect.runtime.JavaUniverse universeRef = new WeakReference[JavaUniverse](result) result } } } class ScalaParameterNameDiscoverer extends ParameterNameDiscoverer { import ScalaParameterNameDiscoverer._ @tailrec private def isScala(cls: Class[_]): Boolean = cls.getEnclosingClass match { case null => ScalaSignatureClasses.exists(ac => cls.getAnnotation(ac) != null) case encls => isScala(encls) } private def discoverNames(u: JavaUniverse)(executable: Executable, symbolPredicate: u.Symbol => Boolean): Array[String] = { import u._ val declaringClass = executable.getDeclaringClass val mirror = runtimeMirror(declaringClass.getClassLoader) val ownerSymbol = if (Modifier.isStatic(executable.getModifiers)) mirror.moduleSymbol(declaringClass).moduleClass.asType else mirror.classSymbol(declaringClass) def argErasuresMatch(ms: MethodSymbol) = ms.paramLists.flatten.map(s => mirror.runtimeClass(s.typeSignature)) == executable.getParameterTypes.toList def paramNames(ms: MethodSymbol) = ms.paramLists.flatten.map(_.name.toString).toArray ownerSymbol.toType.members .find(s => symbolPredicate(s) && argErasuresMatch(s.asMethod)) .map(s => paramNames(s.asMethod)) .orNull } def getParameterNames(ctor: Constructor[_]): Array[String] = if (JdkAtLeast8 && ctor.getParameters.forall(_.isNamePresent)) ctor.getParameters.map(_.getName) else if (isScala(ctor.getDeclaringClass)) discoverNames(universe)(ctor, s => s.isConstructor) else null def getParameterNames(method: Method): Array[String] = { val declaringCls = method.getDeclaringClass if (JdkAtLeast8 && method.getParameters.forall(_.isNamePresent)) method.getParameters.map(_.getName) else if (isScala(declaringCls)) { // https://github.com/scala/bug/issues/10650 val forStaticForwarder = if (Modifier.isStatic(method.getModifiers)) Class.forName(declaringCls.getName + "$", false, declaringCls.getClassLoader) .recoverToOpt[ClassNotFoundException] .flatMap(_.getMethod(method.getName, method.getParameterTypes: _*).recoverToOpt[NoSuchMethodException]) .map(getParameterNames) else Opt.Empty forStaticForwarder.getOrElse( discoverNames(universe)(method, s => s.isMethod && s.name.toString == method.getName)) } else null } }
Example 7
Source File: Container.scala From ncdbg with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.programmaticallyspeaking.ncd.ioc import java.lang.reflect.Constructor def newInstance[R](clazz: Class[_], creator: (Class[_], Seq[Any]) => R): R = { val ca = constructionFor(clazz) creator(clazz, ca._2) } private def constructionFor(clazz: Class[_]): (Constructor[_], Seq[AnyRef]) = { clazz.getConstructors.toList match { case c :: Nil => val args = c.getParameterTypes.map(findReference) (c, args) case _ :: _ => throw new IllegalArgumentException(s"Class $clazz has multiple public constructors") case Nil => throw new IllegalArgumentException(s"Class $clazz has no public constructor") } } } object Container { val empty: Container = new Container(Seq.empty) }
Example 8
Source File: ParamsSequence.scala From seahorse with Apache License 2.0 | 5 votes |
package ai.deepsense.deeplang.params import java.lang.reflect.Constructor import scala.reflect.runtime.universe._ import spray.json._ import ai.deepsense.deeplang.TypeUtils import ai.deepsense.deeplang.exceptions.DeepLangException import ai.deepsense.deeplang.params.exceptions.NoArgumentConstructorRequiredException import ai.deepsense.models.json.graph.GraphJsonProtocol.GraphReader case class ParamsSequence[T <: Params]( override val name: String, override val description: Option[String]) (implicit tag: TypeTag[T]) extends Param[Seq[T]] { val parameterType = ParameterType.Multiplier override def valueToJson(value: Seq[T]): JsValue = { val cells = for (params <- value) yield params.paramValuesToJson JsArray(cells: _*) } private val constructor: Constructor[_] = TypeUtils.constructorForTypeTag(tag).getOrElse { throw NoArgumentConstructorRequiredException(tag.tpe.typeSymbol.asClass.name.decodedName.toString) } private def innerParamsInstance: T = constructor.newInstance().asInstanceOf[T] override def valueFromJson(jsValue: JsValue, graphReader: GraphReader): Seq[T] = jsValue match { case JsArray(vector) => for (innerJsValue <- vector) yield { innerParamsInstance.setParamsFromJson(innerJsValue, graphReader) } case _ => throw new DeserializationException(s"Cannot fill parameters sequence" + s"with $jsValue: array expected.") } override def extraJsFields: Map[String, JsValue] = Map( "values" -> innerParamsInstance.paramsToJson ) override def replicate(name: String): ParamsSequence[T] = copy(name = name) override def validate(value: Seq[T]): Vector[DeepLangException] = { value.flatMap(_.validateParams).toVector } }
Example 9
Source File: ConcreteClassNode.scala From seahorse with Apache License 2.0 | 5 votes |
package ai.deepsense.deeplang.catalogs.doperable import java.lang.reflect.Constructor import ai.deepsense.deeplang.catalogs.doperable.exceptions.NoParameterlessConstructorInClassException import ai.deepsense.deeplang.{DOperable, TypeUtils} private[doperable] class ConcreteClassNode(javaType: Class[_]) extends ClassNode(javaType) { val constructor: Constructor[_] = TypeUtils.constructorForClass(javaType) match { case Some(parameterLessConstructor) => parameterLessConstructor case None => throw NoParameterlessConstructorInClassException(this.javaTypeName) } private[doperable] def createInstance[T <: DOperable]: T = { TypeUtils.createInstance[T](constructor.asInstanceOf[Constructor[T]]) } override private[doperable] def subclassesInstances: Set[ConcreteClassNode] = { super.subclassesInstances + this } }
Example 10
Source File: InvokableConstructor.scala From portable-scala-reflect with BSD 3-Clause "New" or "Revised" License | 5 votes |
package org.portablescala.reflect import java.lang.reflect.Constructor def newInstance(args: Any*): Any = { try { ctor.newInstance(args.asInstanceOf[Seq[AnyRef]]: _*) } catch { case e: java.lang.reflect.InvocationTargetException => val cause = e.getCause if (cause == null) throw e else throw cause } } }
Example 11
Source File: ParamsSequence.scala From seahorse-workflow-executor with Apache License 2.0 | 5 votes |
package io.deepsense.deeplang.params import java.lang.reflect.Constructor import scala.reflect.runtime.universe._ import spray.json._ import io.deepsense.deeplang.TypeUtils import io.deepsense.deeplang.exceptions.DeepLangException import io.deepsense.deeplang.params.exceptions.NoArgumentConstructorRequiredException case class ParamsSequence[T <: Params]( override val name: String, override val description: Option[String]) (implicit tag: TypeTag[T]) extends Param[Seq[T]] { val parameterType = ParameterType.Multiplier override def valueToJson(value: Seq[T]): JsValue = { val cells = for (params <- value) yield params.paramValuesToJson JsArray(cells: _*) } private val constructor: Constructor[_] = TypeUtils.constructorForType(tag.tpe).getOrElse { throw NoArgumentConstructorRequiredException(tag.tpe.typeSymbol.asClass.name.decodedName.toString) } private def innerParamsInstance: T = constructor.newInstance().asInstanceOf[T] override def valueFromJson(jsValue: JsValue): Seq[T] = jsValue match { case JsArray(vector) => for (innerJsValue <- vector) yield { innerParamsInstance.setParamsFromJson(innerJsValue) } case _ => throw new DeserializationException(s"Cannot fill parameters sequence" + s"with $jsValue: array expected.") } override def extraJsFields: Map[String, JsValue] = Map( "values" -> innerParamsInstance.paramsToJson ) override def replicate(name: String): ParamsSequence[T] = copy(name = name) override def validate(value: Seq[T]): Vector[DeepLangException] = { value.flatMap(_.validateParams).toVector } }
Example 12
Source File: DOperationsCatalog.scala From seahorse-workflow-executor with Apache License 2.0 | 5 votes |
package io.deepsense.deeplang.catalogs.doperations import java.lang.reflect.Constructor import scala.collection.mutable import scala.reflect.runtime.{universe => ru} import io.deepsense.deeplang.catalogs.doperations.exceptions._ import io.deepsense.deeplang.{DOperation, TypeUtils} def registerDOperation(category: DOperationCategory, factory: () => DOperation, visible: Boolean = true): Unit } object DOperationsCatalog { def apply(): DOperationsCatalog = new DOperationsCatalogImpl private class DOperationsCatalogImpl() extends DOperationsCatalog { var categoryTree = DOperationCategoryNode() var operations = Map.empty[DOperation.Id, DOperationDescriptor] private val operationFactoryByOperationId = mutable.Map.empty[DOperation.Id, () => DOperation] def registerDOperation(category: DOperationCategory, factory: () => DOperation, visible: Boolean = true): Unit = { val operationInstance = factory() operationInstance.validate() val id = operationInstance.id val name = operationInstance.name val description = operationInstance.description val inPortTypes = operationInstance.inPortTypes.map(_.tpe) val outPortTypes = operationInstance.outPortTypes.map(_.tpe) val parameterDescription = operationInstance.paramsToJson val operationDescriptor = DOperationDescriptor( id, name, description, category, operationInstance.hasDocumentation, parameterDescription, inPortTypes, operationInstance.inPortsLayout, outPortTypes, operationInstance.outPortsLayout ) if (operations.contains(id)) { val alreadyRegisteredOperation = operations(id) throw new RuntimeException( s"Trying to register operation '$name' with UUID $id, " + s"but there is already operation '${alreadyRegisteredOperation.name}' with the same UUID value. " + s"Please change UUID of one of them.") } operations += id -> operationDescriptor if(visible) { categoryTree = categoryTree.addOperation(operationDescriptor, category) } operationFactoryByOperationId(id) = factory } def createDOperation(id: DOperation.Id): DOperation = operationFactoryByOperationId.get(id) match { case Some(factory) => factory() case None => throw DOperationNotFoundException(id) } } }
Example 13
Source File: ConcreteClassNode.scala From seahorse-workflow-executor with Apache License 2.0 | 5 votes |
package io.deepsense.deeplang.catalogs.doperable import java.lang.reflect.Constructor import io.deepsense.deeplang.catalogs.doperable.exceptions.NoParameterlessConstructorInClassException import io.deepsense.deeplang.{DOperable, TypeUtils} private[doperable] class ConcreteClassNode(javaType: Class[_]) extends ClassNode(javaType) { val constructor: Constructor[_] = TypeUtils.constructorForClass(javaType) match { case Some(parameterLessConstructor) => parameterLessConstructor case None => throw NoParameterlessConstructorInClassException(this.javaTypeName) } private[doperable] def createInstance[T <: DOperable]: T = { TypeUtils.createInstance[T](constructor) } override private[doperable] def subclassesInstances: Set[ConcreteClassNode] = { super.subclassesInstances + this } }