Invoking Properties Using Reflection

posted by Bryan on

In reworking some code, I wanted to leverage some lazy loading goodness for properties of a class. Yet at the same time, return a list of all those properties for iterating. Reflection is an awesome way to accomplish this feat!

Reflection is a way to dynamically analyze objects through code and invoke them if needed. I work with automating HTML elements on web pages, so there could be dozens and dozens of these implementations. MappedPage is the base abstract class. Here is what one of my classes looked like:

public class HomePage : MappedPage
{
    public HomePage() : base(/*base constructor arguments*/)
    {
    }

    public MappedElement link_More
    {
        //creates a MappedElement object (a way for our framework to locate an HTML element on the page
        get { return Create(MappedElementType.LINK, MappedAttributeType.ID, "more"); }
    }

    /* Long list of potential HTML elements on a page */
}

The list of properties could range from 1 to 100. However, I wanted to provide the ability to iterate through those elements (properties). Here is how I accomplished it:

private readonly List< MappedElement > _elements = new List< MappedElement >();

public List< MappedElement > GetElements()
{
    if (_elements.Count.Equals(0))
    {
        foreach (PropertyInfo propertyInfo in this.GetType().GetProperties())
        {
            if (propertyInfo.PropertyType.Name.Equals("MappedElement"))
            {
                Type type = this.GetType();
                MethodInfo methodInfo = propertyInfo.GetGetMethod();
                methodInfo.Invoke(this, null);
                object o = type.InvokeMember(propertyInfo.Name, BindingFlags.GetProperty, null, this, null);
                _elements.Add((MappedElement)o);
            }
        }
    }
     return _elements;
}

GetProperties() is a method that you can call on a Type of an object. It will return a list of all Properties of the instantiated object. Then, I loop through to check the Property Type. This is the Return type of the property. In my case, I was returning a MappedElement object. I had to add this check because I have other properties on the class (page title, url, etc).

Then, I was able to invoke the property inside the inner IF statement. This would have been the same as:

HomePage home = new HomePage();
Console.Out.WriteLine(home.link_More);

However, now it is dynamic and I don't have to worry about how many elements there might be. The GetElements() method will only return the correct list and the user can implement over that list easily.

Leave a comment

blog comments powered by Disqus