How to execute a method on a static class using reflection

by Heathesh 1. December 2009 22:49

First, create a method like so:

    /// <summary>
    /// Execute a method on an assembly's static class
    /// </summary>
    /// <param name="assemblyNamespace">The namespace of the assembly you would like to invoke</param>
    /// <param name="className">The name of the class in the assembly you would like to invoke</param>
    /// <param name="methodToExecute">The name of the method in the class to invoke</param>
    /// <param name="parameters">array of objects to be passed into the method we're invoking</param>
    /// <returns>object of whatever the method invoked returns</returns>
    public static object ExecuteMethod(string assemblyNamespace, string className, string methodToExecute,
        params object[] parameters)
    {
        Assembly assembly = Assembly.Load(assemblyNamespace);
        Type classType = assembly.GetType(string.Format("{0}.{1}", assemblyNamespace, className));
        MethodInfo methodInfo = classType.GetMethod(methodToExecute);
        return methodInfo.Invoke(null, parameters);
    }

Make sure you add the relevant using:

    using System.Reflection;

Now we need to call the method. The method I want to invoke is in this class:

    namespace Demo.BusinessLogic
    {
        /// <summary>
        /// User manager class to create, read, update and delete users
        /// </summary>
        public static class UserManager
        {
            /// <summary>
            /// Method to retrieve a User
            /// </summary>
            /// <param name="userId"></param>
            /// <returns></returns>
            public static User Read(int userId)
            {
                User user = new User();

                //TODO add code to retrieve user for Id here

                return user;
            }
        }
    }


To call the method and execute Read the user id 12, I'm going to simply do this:

    object returnedObject = ExecuteMethod("Demo.BusinessLogic", "UserManager", "Read", 12);

And returnedObject comes back populated with my user object!

Tags: , , , ,

Development | .Net

Comments are closed



Powered by BlogEngine.NET 1.5.0.7 (with enhancements by Heathesh)
Theme by Mads Kristensen (with tweeks by Heathesh)

Certifications

Microsoft Certified Professional

Microsoft Certified Technology Specialist

Answer Questions

 

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

http://heathesh.com