Android Question Getting property through reflection?

Troberg

Well-Known Member
Licensed User
I want to get a property of an object of (semi)unknown type. By that, I meant that I don't know exactly what type the object is, but I know that it has the property.

I've tried this, but it fails (java.lang.RuntimeException: java.lang.NoSuchFieldException: MenuPresence):

B4X:
Sub GetProperty(obj As Object, Property As String) As Object
  Dim r As Reflector
  r.Target = obj
  Return r.GetPublicField(Property)
End Sub
Of course, I can do it like this:

B4X:
Sub GetProperty(obj AsObject, Property AsString) AsObject
  ReturnCallSub(obj, "get" & Property)
End Sub
However, that assumes that all properties have getters and setters, and are not simply public variables of the class.

What am I doing wrong here???
 

Troberg

Well-Known Member
Licensed User
The actual field name is _<lower cased field name>.
Thanks, that would have taken me a lot of time to figure out.

Is ReturnCallSub a new b4a keyword/function?
Nope, much simpler than that. Sometimes when I copy-paste from the IDE to the web browser, some spaces are lost (for example, every space after "As"). Don't know why, but it happens.
 
Top