Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active April 2, 2023 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/88de2aec50f51fd3939523eb77b4dfef to your computer and use it in GitHub Desktop.
Save dacr/88de2aec50f51fd3939523eb77b4dfef to your computer and use it in GitHub Desktop.
Obtain the class type of a generic type at runtime / published by https://github.com/dacr/code-examples-manager #62dcc5ac-2855-454b-9350-0f9c1e98c2fb/30bf5edcde581c81c4e18ec003d2098775b2a56b
// summary : Obtain the class type of a generic type at runtime
// keywords : scala, language-feature, class, classtag, generics, reflect, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 62dcc5ac-2855-454b-9350-0f9c1e98c2fb
// created-on : 2022-01-22T08:18:18+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.1.1"
// ---------------------
import scala.reflect.ClassTag
// Won't compile
// def checkKO[T](): Option[T] =
// println(classOf[T].getCanonicalName)
// None
def check[T]()(implicit tag: ClassTag[T]): Option[T] =
val genericTypeClass = tag.runtimeClass.asInstanceOf[Class[T]]
println(genericTypeClass.getCanonicalName)
None
case class Bidule(name: String)
check[String]()
check[Double]()
check[Bidule]()
check[java.awt.Image]()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment