Android Question Possible to get property names from custom type?

Sandman

Expert
Licensed User
Longtime User
Using maps we can use .Keys to get all the keys. I know a custom type isn't a map, but I just wanted to check if it was possible to get the property names from it?

(I have many custom types, and many of them are populated with maps from my server. I wanted to make a naïve "verify that the custom type and the incoming map holds the same properties/keys before actually considering it valid and converting the map to an instance of the custom type". Defensive programming, basically.)
 

stevel05

Expert
Licensed User
Longtime User
There is no direct way but it's possible using reflection. Probably won't be lightning fast though so it depends on the use whether it's worth it.

B4X:
Private Sub GetTypeFieldNames(TType As Object) As List
  
    Dim ThisClass As Reflector
  
    ThisClass.Target  = TType.As(JavaObject).RunMethod("getClass",Null)
  
    Dim Fields() As Object = ThisClass.RunMethod("getFields")
  
    Dim FieldList As List
    FieldList.Initialize
  
    For Each Field As JavaObject In Fields
        Dim FieldStr As String = Field.RunMethod("toGenericString",Null)
        FieldStr = FieldStr.SubString(FieldStr.LastIndexOf(".") + 1)
        If FieldStr = "IsInitialized" Then Continue
      
        FieldList.Add(FieldStr)
    Next
  
    Return FieldList
End Sub

Usage:

B4X:
Dim Fields As List = GetTypeFieldNames(TestType)
  
For Each Field As String In Fields
    Log(Field)
Next
 
Last edited:
Upvote 1
Top