D
D
Dmitry2019-10-07 21:48:29
Scala
Dmitry, 2019-10-07 21:48:29

How to get a class from a type passed as a parameter to the constructor of another class?

Let's say we have a case class and we want to read its fields.
We do so

case class Product (name: String, price: Int)
val fields = classOf[Product].getDeclaredFields

And now we want to pass Product as a type parameter to the constructor of some generic class that would read the fields of the passed type
class SqlModels[T] {
// Здесь охота прочитать поля из T
}

val sqlInstance = new SqlModels[Product]

Is this possible, if so how?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Moseychuk, 2019-10-08
@dimoff66

You need a ClassTag

import scala.reflect._

case class Product(name: String, price: Int)

class SqlModels[T : ClassTag] {
  def fields = classTag[T].runtimeClass.getDeclaredFields
}

But as I understand it, you want to implement something like orm. Then take a look at TypeTag . This is a more powerful counterpart.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question