All Downloads are FREE. Search and download functionalities are using the official Maven repository.

xgi.ut.dsl.utl.ReflectionWrapper.scala Maven / Gradle / Ivy

The newest version!
/*
 *   ScenarLang a domain specific language that attempts to make it even easier
 *   to write unit tests with mockito
 *    
 *   Copyright (C) 2012  X. Gillard 
 *   
 *   This library is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public
 *   License as published by the Free Software Foundation; either
 *   version 2.1 of the License, or (at your option) any later version.
 *   
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *   Lesser General Public License for more details.
 *   
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with this library; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package xgi.ut.dsl.utl

import java.lang.reflect.Field
import xgi.ut.dsl.interpreters.ConversionConfigInterpreter
import java.lang.reflect.Modifier

/**
 * This object provides a scala wrapper around the java reflection api.
 * => serves almost the same purpose as ReflectionUtil : I should consider merging it with that class
 */
object ReflectionWrapper extends ConversionConfigInterpreter {
  // WRAPPERS AROUND JAVA REFLECTION API
  def getField(target:Any, name:String)(implicit clazz:Class[_]=target.getClass):Field = {
    val field = ReflectionUtil.getAllFields(clazz).get(name)
    field.setAccessible(true)
    field
  }
  
  def getFieldType(target:Any, name:String)(implicit clazz:Class[_]=target.getClass):Class[_] = getField(clazz, name).getType
  def getFieldValue(target:Any, name:String)(implicit clazz:Class[_]=target.getClass):Any = {
    val field = getField(clazz, name)
    if(target==null && !Modifier.isStatic(field.getModifiers)) throw new RuntimeException("You are accessing an instance field (%s) iso a static member".format(name))
    field.get(target)
  }
  
  /* 
   * sets the value of the field identified by name for the instance target
   * 
   *  Note: if the value is a string and we know, the field type, this method will
   *  attempt to convert the value to the appropriate type
   */
  def setField(target:Any, name:String, value:Any)(implicit clazz:Class[_]=target.getClass) = {
    val field = getField(clazz, name)
    val fieldType = field.getType
    val valueToSet = value match {
      case text:String => convert(text, fieldType)
      case _ => ReflectionUtil.autoBox(value, fieldType)
    }
    field.set(target, valueToSet)
  }
  
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy