How to call shared methods by string name?

  • Thread starter Thread starter Don
  • Start date Start date
D

Don

Is it possible to call a shared method of a class when you have both the
name of the class and the name of the method of that class that you want to
invoke stored in strings? If so, can this be done for singleton classes
(i.e. classes with only shared members and with a private instance
constructor)?

- Don
 
Don said:
Is it possible to call a shared method of a class when you have both
the name of the class and the name of the method of that class that
you want to invoke stored in strings? If so, can this be done for
singleton classes (i.e. classes with only shared members and with a
private instance constructor)?


Class Form1
Shared Sub test()

End Sub

Sub AnyWhere
Type.GetType("Rootnamespace.Form1").GetMethod("test").Invoke( _
Nothing, Nothing _
)
End Sub

End Class



Armin
 
Armin Zingler said:
Type.GetType("Rootnamespace.Form1").GetMethod("test").Invoke( _
Nothing, Nothing _
)

I was a little thrown off by the inclusion of the Rootnamespace in the type
name, thinking I could use it to reference namespaces of referenced
libraries. That didn't work. However, the following did work:


' Get the referenced assembly that contains the class
Dim asm As System.Reflection.Assembly = _
System.Reflection.Assembly.LoadWithPartialName("AssemblyName")

' Get the class's type
Dim typ As Type = asm.GetType("AssemblyName.ClassType", True, True)

' Get the method we want to execute
Dim mi As System.Reflection.MethodInfo = typ.GetMethod("MethodName")

' Execute method
mi.Invoke(Nothing, Nothing)

' Alternatively: Execute method with arguments
'mi.Invoke(Nothing, New Object() {arg1, arg2, arg3})


Or, as one line:

System.Reflection.Assembly.LoadWithPartialName("AssemblyName").GetType("Asse
mblyName.ClassType", True, True).GetMethod("MethodName").Invoke(Nothing,
Nothing)


- Don
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top