Search code examples
c#javareflectionprogramming-languages

What is Reflection property of a programming language?


Its said that most high-level dynamically types languages are reflexive. Reflection (computer programming) on Wikipedia explains but it doesn't really give a very clear picture of what it means. Can anyone explain it in a simpler way by a relevant example?


Solution

  • To give you a example how to use Reflection in a practical way:

    Let's assume you are developing an Application which you'd like to extend using plugins. These plugins are simple Assemblies containing just a class named Person:

    namespace MyObjects
    {
        public class Person
        {
            public Person() { ... Logic setting pre and postname ... }
            private string _prename;
            private string _postname;
            public string GetName() { ... concat variabes and return ... }
        }
    }
    

    Well, plugins should extend your application at runtime. That means, that the content and logic should be loaded from another assembly when your application already runs. This means that these resources are not compiled into your Assembly, i.e. MyApplication.exe. Lets assume they are located in a library: MyObjects.Person.dll.

    You are now faced with the fact that you'll need to extract this Information and for example access the GetName() function from MyObjects.Person.

    // Create an assembly object to load our classes
    Assembly testAssembly = Assembly.LoadFile(Application.StartUpPath + @"MyObjects.Person.dll");
    Type objType = testAssembly.GetType("MyObjects.Person");
    
    // Create an instace of MyObjects.Person
    var instance = Activator.CreateInstance(objType);
    
    // Call the method
    string fullname = (string)calcType.InvokeMember("GetName",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
    null, instance, null);
    

    As you can see, you could use System.Reflection for dynamic load of Resources on Runtime. This might be a help understanding the ways you can use it.

    Have a look on this page to see examples how to access assemblys in more detail. It's basically the same content i wrote.