Home > Blockchain >  Recursively get private field value using reflection
Recursively get private field value using reflection

Time:10-21

I've got a deeply nested private fields chain which I'd like to iterate recursively to get the value of some target field.

How can this be done?

For example:

public class A
{
   private B b;
   public A(B b) { this.b = b; }
}

public class B
{
   private C[] cItems;
   public B(C[] cItems) { this.cItems = cItems; }
}

public class C
{
   private string target; // <-- get this value
   public C(int target) { this.target = val; }
}
public static void GetFieldValueByPath(object targetObj, string targetFieldPath)
{
   // how to do it? I self-answer below 
}

Usage will be:

public void DoSomething(A a)
{
   var val = GetFieldValueByPath(a, "b.cItems[2].target");
}
  • Notes:
    • There is a related question about recursively getting properties, but not fields. But even then, it doesn't support array fields.
    • Related questions such as this one for getting fields are not recursive.

CodePudding user response:

The code works for your example, but you may need to change it in case of having Dictionaries

public static object GetFieldValueByPath(object targetObj, string targetFieldPath)
        {
            var fieldNames = targetFieldPath.Split('.');
            var type = targetObj.GetType();

            foreach (var fieldName in fieldNames)
            {
                string name = fieldName;
                int? objectIndex = default;
                if (name.Contains('['))//getting fieldName without indexer
                {
                    int indexerStart = name.IndexOf('[');
                    int indexerEnd = name.IndexOf(']');

                    objectIndex = int.Parse(name.Substring(indexerStart   1, indexerEnd-indexerStart - 1));
                    name = name.Substring(0, indexerStart);
                }

                var field = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Instance);
                if (objectIndex.HasValue)//here we know that field is collection
                {
                    targetObj=((IList<object>)field.GetValue(targetObj))[0];//getting item by index
                    type = targetObj.GetType();
                }
                else
                {
                    targetObj = field.GetValue(targetObj);
                    type = field.FieldType;
                }
            }

            return targetObj;
        } 

CodePudding user response:

OfirD's answer is on the right track, but it won't work. Not only does it not compile, but C[] does not implement IList<object>.

It also has quite a few scenarios that it does not account for. (I have not updated his code to account for these scenarios)

  • What if the array does not get indexed by an integer?
  • What if it is a jagged array?
  • What if the path points to properties instead of fields?

I've updated his code to work:

    public static object GetFieldValueByPath(object obj, string fieldPath)
    {
        var flags =
            BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
        var splitted = fieldPath.Split('.');

        var current = splitted[0];
        int? index = null;

        // Support getting a certain index in an array field
        var match = Regex.Match(current, @"\[([0-9] )\]");
        if (match.Groups.Count > 1)
        {
            current = fieldPath.Substring(0, match.Groups[0].Index);
            index = int.Parse(match.Groups[1].Value);
        }

        var value = obj.GetType().GetField(current, flags).GetValue(obj);


        if (value == null)
        {
            return null;
        }

        if (splitted.Length == 1)
        {
            return value;
        }

        if (index != null)
        {
            value = Index(value, index.Value);
        }

        return GetFieldValueByPath(value, string.Join(".", splitted.Skip(1)));
    }

    static object Index(object obj, int index)
    {
        var type = obj.GetType();
        foreach (var property in obj.GetType().GetProperties())
        {
            var indexParams = property.GetIndexParameters();
            if (indexParams.Length != 1) continue;
            return property.GetValue(obj, new object[] { index });
        }

        throw new Exception($"{type} has no getter of the format {type}[int]");
    }

CodePudding user response:

Here's the way to do it (this also supports getting to a certain index in an array field):

Full Demo

Usage:

public static void Main(string[] s)
{
    var a1 =  new A(new B(new C[] { new C(1), new C(2), new C(3) } ) );
    Console.WriteLine(GetFieldValueByPath(a1, "b.cItems[2].target"));
            
    var a2 =  new A(new B(new C[] { } ) );
    Console.WriteLine(GetFieldValueByPath(a2, "b.cItems[2].target"));
            
    var a3 =  new A(new B(null) );
    Console.WriteLine(GetFieldValueByPath(a3, "b.cItems[2].target"));
}

Implementation:

public static object GetFieldValueByPath(object obj, string fieldPath)
{
    var flags = 
        BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
    var splitted = fieldPath.Split('.');

    var current = splitted[0];
    int? index = null;

    // Support getting a certain index in an array field
    var match = Regex.Match(current, @"\[([0-9] )\]");
    if (match.Groups.Count > 1)
    {
        current = fieldPath.Substring(0, match.Groups[0].Index);
        index = int.Parse(match.Groups[1].Value);
    }
          
    object value;
    try
    {
        value = obj.GetType().GetField(current, flags).GetValue(obj);
    }
    catch (NullReferenceException ex)
    {
        throw new Exception($"Wrong path provided: field '{current}' does not exist on '{obj}'");
    }
            
    if (value == null)
    {
        return null;
    }
            
    if (splitted.Length == 1)
    {
        return value;
    }

    if (index != null)
    {
        var asIList = (IList<object>)value;
        if (asIList?.Count >= index.Value)
        {
            value = asIList[index.Value];
        }
        else
        {
            return null;
        }
    }

    return GetFieldValueByPath(value, string.Join(".", splitted.Skip(1)));
}
  • Related