Reputation: 17602
If I have a small Scala class with a private field and public accessors:
class Entity {
private var _name:String = ""
def name:String = <some stuff>
def name_=(v:String) = <some stuff>
}
How can I invoke these accessors using Java reflection?
The class may be 3rd party code, or at least really hard to change. Please note that making the underlying field accessible will not allow us to call the code in the accessors, which is what I'm really after.
Upvotes: 2
Views: 1553
Reputation: 14202
The accessors are simply methods named name
and name_$eq
so you can do this in Java too:
scala> val c = classOf[Entity]
c: java.lang.Class[Entity] = class Entity
scala> c.getDeclaredMethod("name_$eq", classOf[String])
res0: java.lang.reflect.Method = public void Entity.name_$eq(java.lang.String)
scala> c.getDeclaredMethod("name")
res1: java.lang.reflect.Method = public java.lang.String Entity.name()
Upvotes: 7