Call class by string

Aquarius

New member
Joined
Nov 9, 2009
Messages
2
Programming Experience
5-10
Hi. This is my first post.

I have database with class names listed in string field.
I want to circle thru records and call certain class.

Eg.

Data table
ID ClassName
1 ClsCreateButton
2 ClsCreatePanel

After retriving this data in dataset(ds.tblClass) I want to do next:

Dim aClass as New ds.tblClass("ClassName")
Do something with aClass...

I would apiciated your help.
 
If you have limited types you can do a Select Case and hardcode the types:
VB.NET:
Select Case classname
   Case "ClassA"
      Dim b As New ClassA
      b.Method
   Case "ClassB"
      Dim b As New ClassB
      b.Method
End Select
You can also use Reflection and the type system for dynamic code, let's say the executing assembly contains a Test class in WindowsApplication1 namespace:
VB.NET:
Public Class Test
    Public Sub Method()
        MsgBox("hello")
    End Sub
End Class
VB.NET:
Dim t As Type = Reflection.Assembly.GetExecutingAssembly.GetType("WindowsApplication1.Test")
Dim o As Object = Activator.CreateInstance(t)
t.GetMethod("Method").Invoke(o, Nothing)
As you see the instance created can only be treated as Object here, if you're using a specific type you have to know at design time which type that is created, ie like the Select Case example above.

Useful with reflection is in some cases to use interfaces, to write strong type code with different dynamic types. There could for example be this interface and same Test class that implement it:
VB.NET:
Public Interface IMethods
    Sub Method()
End Interface

Public Class Test
    Implements IMethods

    Public Sub Method() Implements IMethods.Method
        MsgBox("hello")
    End Sub
End Class
The reflection code could then use the IMethods type:
VB.NET:
Dim t As Type = Reflection.Assembly.GetExecutingAssembly.GetType("WindowsApplication1.Test")
Dim i As IMethods = CType(Activator.CreateInstance(t), IMethods)
i.Method()
Naturally, other types could implement the same interface and your reflection code could create instances and handle them as same IMethods type.
 
This is it. Thx!!!

Well, some serios guys are runing arround.
Thanx JohnH. It was fast, sharp, clean and very understandible.
 
Back
Top