Instantiate an Object Using Reflection - CSharp Reflection

CSharp examples for Reflection:Type

Description

Instantiate an Object Using Reflection

Demo Code


using System;/* w  ww .ja v  a2s. co  m*/
using System.Text;
using System.Reflection;

class MainClass
    {
        public static StringBuilder CreateStringBuilder()
        {
            Type type = typeof(StringBuilder);

            Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) };

            ConstructorInfo cInfo = type.GetConstructor(argTypes);

            object[] argVals = new object[] { "Some string", 30 };

            StringBuilder sb = (StringBuilder)cInfo.Invoke(argVals);

            return sb;
        }
    }

    public interface Car
    {
        string Description { get; set; }
        void Start();
        void Stop();
    }

    public abstract class AbstractCar : Car
    {
        private string description = "";

        public string Description
        {
            get { return description; }
            set { description = value; }
        }

        public abstract void Start();
        public abstract void Stop();
    }

    public class SimpleCar : AbstractCar
    {
        public override void Start()
        {
            Console.WriteLine(Description + ": Starting...");
        }

        public override void Stop()
        {
            Console.WriteLine(Description + ": Stopping...");
        }
    }

    public sealed class CarFactory
    {
        public static Car CreateCar(string assembly,string pluginName, string description)
        {
            Type type = Type.GetType(pluginName + ", " + assembly);

            ConstructorInfo cInfo = type.GetConstructor(Type.EmptyTypes);

            Car plugin = cInfo.Invoke(null) as Car;

            plugin.Description = description;

            return plugin;
        }

        public static void Main(string[] args)
        {
            Car plugin = CarFactory.CreateCar(
                "Main",  // Private assembly name
                "Main", // Car class name
                "A Simple Car"       // Car instance description
            );

            plugin.Start();
            plugin.Stop();

        }
    }

Result


Related Tutorials