Creating a new class instance using Introspection

From REALbasicWiki

Jump to: navigation, search

With RB version 2008r2 and later, one can effectively store a class's name in a variable (property) using Introspection.

As an example, consider having many subclasses, and depending on dynamic rules, you later need to instantiate either of them from a central point again.

[edit] The old way

Here's the old way to do it. First, each class identifies itself somehow:

class A
function ClassID () as String
return "ThisIsClassA"
end function
end

class B
function ClassID () as String
return "ThisIsClassB"
end function
end

And now its counterpart, the code that recreates a class from the ID:

function newInstanceFromClassID (id as String) as Object
select case id
case "ThisIsClassA"
return new A
case "ThisIsClassB"
return new B
end select
end function

[edit] The New way

Here's the new way using Introspection:

class A
function ClassID () as Introspection.TypeInfo
return Introspection.GetType (me)
end function
end

class B
function ClassID () as Introspection.TypeInfo
return Introspection.GetType (me)
end function
end

Note how both classes use the very same code. This means this could be handled by a single method in a common super class, even.

And its counterpart:

function newInstanceFromClassID (id as Introspection.TypeInfo) as Object
dim cs() as Introspection.ConstructorInfo = id.GetConstructors
return cs(0).Invoke()
end function

[edit] See also

Personal tools
related