Wish Access Fields in Type at Runtime

MarkusR

Well-Known Member
Licensed User
hello,
it seems missing
if we have a type like this one
B4X:
Type Data(a As String,b As Int, c As Float)
dim test as Data
i like to have access this struct via name (and index)
B4X:
test.Field("a") = "abc"
test.Field("b") = 123
something like
B4X:
foreach field in test
log(field)
next
 

Roycefer

Well-Known Member
Licensed User
This is what I've been using. For each field, it returns a String like "FieldName:fully.qualified.field.Type".
B4X:
Sub GetMemberNamesAndTypes(o As Object) As String()
    Dim jo As JavaObject = Me
    Dim fns() As String = jo.RunMethodJO("GetFieldNamesAndTypes",Array(o))
    Return fns
End Sub

#If JAVA
import java.lang.reflect.Field;

public static String[] GetFieldNamesAndTypes(Object o)
{
    Field[] fields = o.getClass().getFields();
    String[] fns = new String[fields.length];
    for(int j=0;j<fields.length;j++)
    {
        fns[j] = fields[j].getName() + ":" + fields[j].getGenericType().getTypeName();
    }
    return fns;
}
#End If
Used on your Type Data, it would look like this:
B4X:
Dim jo As JavaObject = someData 'this of Type Data
For Each field As String in GetMemberNamesAndTypes(someData)
    Dim fieldType As String = Regex.Split(":",field)(1)
    Dim fieldName As String = Regex.Split(":",field)(0)
    Log($"Name: ${fieldName} Type: ${fieldType} Value: ${jo.GetField(fieldName)}"$)
Next
 
Last edited:

MarkusR

Well-Known Member
Licensed User
@Roycefer yes, thanks, something like this build in. i think its very useful for all.
 
Top