本文整理汇总了Scala中java.lang.reflect.Field类的典型用法代码示例。如果您正苦于以下问题:Scala Field类的具体用法?Scala Field怎么用?Scala Field使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Field类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: PreferenceGroupAdapter
//设置package包名称以及导入依赖的类
package be.mygod.preference
import java.lang.reflect.Field
import java.util.List
import android.os.Build
import android.support.v4.content.ContextCompat
import android.support.v4.view.ViewCompat
import android.support.v7.preference.{PreferenceGroup, PreferenceViewHolder, PreferenceGroupAdapter => Old}
import android.view.{LayoutInflater, View, ViewGroup}
import com.github.shadowsocks.R
object PreferenceGroupAdapter {
private var preferenceLayoutsField: Field = _
private var fieldResId: Field = _
private var fieldWidgetResId: Field = _
private val preferenceViewHolderConstructor = classOf[PreferenceViewHolder].getDeclaredConstructor(classOf[View])
{
val oldClass = classOf[Old]
preferenceLayoutsField = oldClass.getDeclaredField("mPreferenceLayouts")
preferenceLayoutsField.setAccessible(true)
val c = oldClass.getDeclaredClasses.filter(c => c.getSimpleName == "PreferenceLayout").head
fieldResId = c.getDeclaredField("resId")
fieldResId.setAccessible(true)
fieldWidgetResId = c.getDeclaredField("widgetResId")
fieldWidgetResId.setAccessible(true)
preferenceViewHolderConstructor.setAccessible(true)
}
}
class PreferenceGroupAdapter(group: PreferenceGroup) extends Old(group) {
import PreferenceGroupAdapter._
protected lazy val preferenceLayouts = preferenceLayoutsField.get(this).asInstanceOf[List[AnyRef]]
override def onCreateViewHolder(parent: ViewGroup, viewType: Int) = if (Build.VERSION.SDK_INT < 21) {
val context = parent.getContext
val inflater = LayoutInflater.from(context)
val pl = preferenceLayouts.get(viewType)
val view = inflater.inflate(fieldResId.get(pl).asInstanceOf[Int], parent, false)
if (view.getBackground == null) {
val array = context.obtainStyledAttributes(null, R.styleable.BackgroundStyle)
var background = array.getDrawable(R.styleable.BackgroundStyle_android_selectableItemBackground)
if (background == null)
background = ContextCompat.getDrawable(context, android.R.drawable.list_selector_background)
array.recycle
val (s, t, e, b) = (ViewCompat.getPaddingStart(view), view.getPaddingTop,
ViewCompat.getPaddingEnd(view), view.getPaddingBottom)
view.setBackground(background)
ViewCompat.setPaddingRelative(view, s, t, e, b)
}
val widgetFrame = view.findViewById(android.R.id.widget_frame).asInstanceOf[ViewGroup]
if (widgetFrame != null) {
val widgetResId = fieldWidgetResId.get(pl).asInstanceOf[Int]
if (widgetResId != 0) inflater.inflate(widgetResId, widgetFrame) else widgetFrame.setVisibility(View.GONE)
}
preferenceViewHolderConstructor.newInstance(view)
} else super.onCreateViewHolder(parent, viewType)
}
示例2: 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
}
}
示例3: isFieldInSuperclass
//设置package包名称以及导入依赖的类
package de.randombyte.nightmare_ai.config
import java.lang.reflect.Field
import com.google.gson.{ExclusionStrategy, FieldAttributes}
def isFieldInSuperclass(superclass: Class[_], fieldName: String): Boolean = {
if (superclass != null) {
if (getField(superclass, fieldName) != null) true
else isFieldInSuperclass(superclass.getSuperclass, fieldName)
} else false
}
def getField(clazz: Class[_], fieldName: String): Field = {
try {
clazz.getDeclaredField(fieldName)
} catch {
case nsfError: NoSuchFieldException => null
}
}
}
示例4: ObjectUtils
//设置package包名称以及导入依赖的类
package pub.ayada.scala.utils
import java.lang.reflect.Field
object ObjectUtils {
def prettyPrint(a: Any): String = {
// Recursively get all the fields; this will grab vals declared in parents of case classes.
def getFields(cls: Class[_]): List[Field] =
Option(cls.getSuperclass).map(getFields).getOrElse(Nil) ++
cls.getDeclaredFields.toList.filterNot(f =>
f.isSynthetic || java.lang.reflect.Modifier.isStatic(f.getModifiers))
a match {
// Make Strings look similar to their literal form.
case s: String =>
'"' + Seq("\n" -> "\\n", "\r" -> "\\r", "\t" -> "\\t", "\"" -> "\\\"", "\\" -> "\\\\").foldLeft(s) {
case (acc, (c, r)) => acc.replace(c, r)
} + '"'
case xs: Seq[_] =>
xs.map(prettyPrint).toString
case xs: Array[_] =>
s"Array(${xs.map(prettyPrint) mkString ", "})"
// This covers case classes.
case p: Product =>
s"${p.productPrefix}(${
(getFields(p.getClass) map { f =>
f setAccessible true
s"${f.getName} = ${prettyPrint(f.get(p))}"
}) mkString ", "
})"
// General objects and primitives end up here.
case q =>
Option(q).map(_.toString).getOrElse("¡null!")
}
}
}
示例5: 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
}
}
示例6: IllegalArityException
//设置package包名称以及导入依赖的类
package org.quicli.model
import java.lang.reflect.Field
import org.quicli.QuicliException
import org.quicli.utils.reflect._
import scala.reflect.runtime.universe._
class IllegalArityException private(message: String) extends QuicliException(message)
object IllegalArityException {
def throwIllegalBoolean(f: Field, a: Arity): Nothing = {
throw new IllegalArityException(s"${commonMessage(f, a)}! A Boolean can take only 0 (default) or 1 arg.")
}
def throwIllegalTuple(f: Field, a: Arity): Nothing = {
throw new IllegalArityException(s"${commonMessage(f, a)}! A TupleN can take only N args which is set by default.")
}
def throwIllegalSingleType(f: Field, a: Arity, typ: Type): Nothing = {
val name: String = typ.simpleName
throw new IllegalArityException(s"${commonMessage(f, a)}! A $name can take only 1 arg. " +
s"You can use collections or arrays (e.g. List[$name], Array[$name]) to support multiple args.")
}
private def commonMessage(f: Field, arity: Arity): String = {
s"Illegal arity of ${arity.value} for ${f.getDeclaringClass.getSimpleName}.${f.getName}"
}
}
示例7: 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)
}
}
示例8: 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)
}
}