Showing posts with label Reflection. Show all posts
Showing posts with label Reflection. Show all posts

Wednesday, March 24, 2010

Invoke method using reflection


We have find out methods of any class using reflection but sometime we need to execute it using reflection.

For example, it might required that you have one logic for calculating pricing information which change time to time then you have to use reflection to calculate price. You can create one assembly to calculate pricing information. Whenever you need to change logic, you have to put new assembly on the same path with new logic.

Before calling any method you have to declare object of that class. You can use Activator class to create object runtime.


object objClass1 = Activator.CreateInstance(type);


The above code will create Class1 object using Activator class.

After loading class object successfully, you have to find out method from that type and invoke it. Following source code helps you to invoke method.


Assembly assembly = Assembly.Load("TestLibrary1");
Type t = assembly.GetType("TestLibrary1.Class1");
MethodInfo method = t.GetMethod("GetSum");
object objClass1 = Activator.CreateInstance(t);
object[] objParameters = new object[2];
objParameters[0] = 10;
objParameters[1] = 11;
MessageBox.Show(method.Invoke(objClass1, objParameters).ToString());


Here we load assembly and find out the class type using “GetType” method of assembly class. After getting class type, we have created class object dynamically using Activator class. Then we find out method which we need to invoke and also create parameter array to pass into method. After creating parameter array, we need to call “Invoke” method of MethodInfo class to invoke the method. Return value of Invoke method is the same which that method returns.

You can download source code from here.

Get Class Members using Reflection


You can find basic information of Reflection from What is Reflection.

You can get members of any class using reflection. Let’s start with constructor.

You can retrieve all constructors using “GetConstructors” method which is available in Type class object. You can get Type class object from loading assembly and find Type using “GetType” method. For loading assembly and find type please click here.

Following code snippet is used to get all constructors from any class.

private void GetConstructors(Type type)
{
ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.CreateInstance | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
foreach (ConstructorInfo constructor in constructors)
{
string constructorString = "";

if (constructor.IsStatic)
constructorString = "static new(";
else if (constructor.IsPrivate)
constructorString = "private new(";
else if (constructor.IsPublic)
constructorString = "public new(";

ParameterInfo[] parameters = constructor.GetParameters();
foreach (ParameterInfo parameter in parameters)
{
constructorString += parameter.ParameterType.Name + " " + parameter.Name + ", ";
}
if(constructorString.EndsWith(", "))
constructorString = constructorString.Substring(0, constructorString.Length - 2);
constructorString += ")";
listBox2.Items.Add(constructorString);
}
}


Here I have not handling error. You can optimize code. I have just draft the code for demo purpose.

We need to call “GetConstructors” method of Type class object which returns ConstructorInfo class array. You can iterate that array and find out constructor information like parameters.

Same way you can find out variables which are declared into class. Following code snippet is used for that:


private void GetVariables(Type type)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
listBox3.Items.Add(field.FieldType.Name + " " + field.Name);
}
}


GetFields class returns all the available variables declared into that type. Here we mentioned Binding Flags which are used to find out type of variable. If you want to find out only private variables then you have to specify “Instance” and “Private” flag only. Here I need to find out Public, Private, Protected and static variables so I have mentioned all required flags.

GetMethods method used to find out list of methods into type. Following code will help you to find out available methods:


private void GetMethods(Type type)
{
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
string methodString = "";

if (method.IsStatic)
methodString = "static " + method.Name + "(";
else if (method.IsPrivate)
methodString = "private " + method.Name + "(";
else if (method.IsPublic)
methodString = "public " + method.Name + "(";

ParameterInfo[] parameters = method.GetParameters();
foreach (ParameterInfo parameter in parameters)
{
methodString += parameter.ParameterType.Name + " " + parameter.Name + ", ";
}
if (methodString.EndsWith(", "))
methodString = methodString.Substring(0, methodString.Length - 2);
methodString += ")";
listBox4.Items.Add(methodString);
}
}


You can also download source code from here.

What is Reflection


Reflection means to find out metadata information of any modules or assembly. You can also create class using reflection.

Developer can load any assembly runtime and find out metadata information of that assembly. He can also create object of any type which are exist in that assembly and also able to assign value and call any method from that object at runtime.

Let’s take an example, you have to use any third party control (DLL). You can get your requested type dynamically.

Here I explained you how to load any assembly which is added as a reference in your project.

You are getting one Test Library1 (TestLibrary1.dll) and you have to find out “Class1” type. You have to add reference of that class library and call this code snippet to load library:


Assembly assembly = Assembly.Load("TestLibrary1");
Type t = assembly.GetType("TestLibrary1.Class1");


Here we have pass “TestLibrary1” as a parameter of Assembly.Load method is an assembly name. This is same as a namespace name.

Assembly is in-built .net class which has static method “Load” which load assembly so developer can easily find out types.

After loading assembly, you can find out your type using GetType method of assembly object.

Load method of Assembly class has different overloads. You can also pass physical path or Assembly name or byte array of assembly name.

You can download code from here.

DotNet Code Guru