Tuesday, April 21, 2009

How to execute (invoke) a function using reflection if we know it's name and class

Have you ever wondered how to do that. This can be useful if you build a custom control and want user to tell you what function to call, for some reason. Code shown bellow.

Public Shared Function CallFunctionByReflection(ByVal className As String, ByVal functionName As String, ByVal arguments As Object())
    Dim theType As Type = Nothing
    Dim theObj As [Object] = Nothing
    Dim theMethodInfo As MethodInfo = Nothing

    theType = System.Type.GetType(className)

    theObj = Activator.CreateInstance(theType)

      theMethodInfo = theType.GetMethod(functionName)

      If arguments IsNot Nothing Then
        Return theMethodInfo.Invoke(theObj, arguments)
        Return theMethodInfo.Invoke(theObj, Nothing)
      End If
    Catch Ex As Exception
      Throw Ex
      Return Nothing
      theType = Nothing
      theObj = Nothing
      theMethodInfo = Nothing
    End Try
  End Function

No comments: