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

org.specs2.reflect.ClassName.scala Maven / Gradle / Ivy

The newest version!
package org.specs2
package reflect

import scala.reflect.NameTransformer
import control.Exceptions._
import text.CamelCase._

/**
 * Utility reflection methods for Class names
 */
private[specs2]
trait ClassName {
  /** @return the class name of an instance */
  def simpleClassName(any: AnyRef): String = simpleName(any.getClass)
  /** @return the class name of an instance */
  def className(any: AnyRef): String = className(any.getClass)
  /**
   * @return the outer class name for a given class
   */
  def getOuterClassName(c: Class[_]): String = {
    c.getDeclaredConstructors.toList(0).getParameterTypes.toList(0).getName
  }
  /**
   * @return the decoded class name, with its package
   */
  def className(name: String): String = {
    val decoded = NameTransformer.decode(name)
    val remainingDollarNames = decoded.split("\\$")
    val result = if (remainingDollarNames.size > 1) {
      if (remainingDollarNames(remainingDollarNames.size - 1).matches("\\d"))
        remainingDollarNames(remainingDollarNames.size - 2)
      else
        remainingDollarNames(remainingDollarNames.size - 1)
    } else remainingDollarNames(0)
    result
  }
  /**
   * @return the class name
   */
  def className(klass: Class[_]): String = className(klass.getName)
  /**
   * @return the class name without the package name
   */
  def simpleName(klass: Class[_]): String = {
    val result = className(klass.getSimpleName)
    if (result.contains("anon") && klass.getSuperclass != null) simpleName(klass.getSuperclass)
    else result
  }
  /**
   * @return the uncamelcased name of the class (or its parent if it is an anonymous class)
   */
  def humanName(c: Class[_]): String =
    if (c.getSimpleName.contains("$"))
      humanName(c.getSuperclass)
    else
      c.getSimpleName.camelCaseToWords
}
private[specs2]
object ClassName extends ClassName




© 2015 - 2024 Weber Informatics LLC | Privacy Policy