Scala get classtag from class instance

803 Views Asked by At

I need to write a generic method to get all fields of an object and it's value, the class of this object may contains ClassTag, so we should find a way to get it as well, is any way good way ? the difficulty is we don't know the class ahead, it may contains ClassTag (zero to many), It may not.

For example,

class A(x : Int) {}

a = new A(1)

We should output x => 1

class B[T: ClassTag]() {}

b = new B[Float]()

We should output _$1 = Float

1

There are 1 best solutions below

2
On BEST ANSWER
def fields(obj: AnyRef) = obj.getClass.getDeclaredFields.map(field => (field.getName, field.get(obj))

will give you an array of pairs of field names and corresponding values, which you can massage into the format you want. You can test for types and do something depending on whether you have a ClassTag or not.

But for your specific examples: neither x in A nor the ClassTag in B are fields, they are just constructor parameters which aren't stored anywhere in the instance. To change this, you can declare it as a val:

class A(private val x: Int)
class B[T]()(private val tag: ClassTag[T])

or make sure they are used somewhere in the body outside the constructor.