Is there a way to generically implement the following (using java reflection)?
class Bar
class Foo {
def getName(param : Bar) : String = ???
}
class MyFoo(a : Bar, b : Bar, c : Bar, d : Bar) extends Foo
object A extends Bar
object B extends Bar
object C extends Bar
object D extends Bar
new Foo(A, B, C, D).getName(C) //prints "c"
I want get the constructor argument name according to the object fed as param
No, if it’s only a constructor parameter, the instance doesn’t retain any reference to the argument. You would need to make them val
s and then compare the values and match up the field names with the parameter names.
Depending on how much you want the constructor parameter name, you can use https://github.com/paul-hammant/paranamer to fish it out of the bytecode. That’s how jackson-module-scala does it to serialize classes to JSON using the constructor parameter names