Wish Access Fields in Type at Runtime

Discussion in 'B4J Bugs & Wishlist' started by MarkusR, Apr 16, 2018.

  1. MarkusR

    MarkusR Well-Known Member Licensed User

    hello,
    it seems missing
    if we have a type like this one
    Code:
    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)
    Code:
    test.Field("a") = "abc"
    test.Field(
    "b") = 123
    something like
    Code:
    foreach field in test
    log(field)
    next
     
  2. Roycefer

    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".
    Code:
    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:
    Code:
    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: Apr 16, 2018
    inakigarm, wl, DonManfred and 2 others like this.
  3. MarkusR

    MarkusR Well-Known Member Licensed User

    @Roycefer yes, thanks, something like this build in. i think its very useful for all.
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice