文字列からクラスのインスタンスを生成 - VB.NET
例) ProjectName.Person
のインスタンスを生成したい
生成対象のクラス(ProjectName.Person
)
Public Class Person Public name As String Public Sub New() Me.name = "hoge" End Sub Public Sub New(ByVal name As String) Me.name = name End Sub End Class
生成するメインモジュール
Module Module1 Sub Main() Dim personType As Type = Type.GetType("ProjectName.Person") ' 引数なしのコンストラクタ Dim personConstructor As ConstructorInfo = personType.GetConstructor(Type.EmptyTypes) ' Stringの引数を持つコンストラクタ Dim personConstructor2 As ConstructorInfo = personType.GetConstructor(New Type() {GetType(String)}) Dim personClassObject As Object = personConstructor.Invoke(New Object() {}) Dim personClassObject2 As Object = personConstructor2.Invoke(New Object() {"太郎"}) Debug.Print(personClassObject.name) Debug.Print(personClassObject2.name) End Sub End Module
出力結果
hoge 太郎
ポイント
Type.GetType()
でクラスの生成{Type}.GetConstructor()
でコンストラクタの生成- 引数なしの場合、
Type.EmptyTypes
- 引数ありの場合、
Type
インスタンスを生成し、渡す
- 引数なしの場合、
{ConstructorInfo}.Invoke()
でインスタンスの生成