Question MARK PONGONIS · Apr 11, 2024

using variable as package/class name to call Class method

Is it possible to use a variable instead the actual class name when calling a class method?

Ex.

s var = "MyPackage.MyClass"

d ##class(var).Main()

Product version: IRIS 2021.1
$ZV: 2021.1.2

Comments

Julius Kavay · Apr 11, 2024

If your class is instantiable (i.e. not an abstarct class) then

set obj = ##class(MyPackage.MyClass).%New()
do obj.Main()
setx=obj.OtherMethod(parameter)
0
Julius Kavay · Apr 11, 2024

The other way is, to put the classname into a variable and

set var = "MyPackage.MyClass"do$classmethod(var,"Main")
setx=$classmethod(var,"Othermethod",params)

// or, if you have an instanceset obj=##class(MyClass).%New()
do$method(obj,"Main")
setx=$method(obj,"Othermethod",params)
0
MARK PONGONIS  Apr 11, 2024 to Julius Kavay

That works great, thanks! What about to instantiate a new object?

Ex. 

s var = "MyClass"

s obj=##class(var).%New()

0
Robert Cemper  Apr 11, 2024 to MARK PONGONIS
set var="MyClass"
execute "set obj=##class("_var_").%New()"

a bit dirty but matches your request

0
liu bo  Apr 11, 2024 to MARK PONGONIS

you can use as following:   s clsName = "MyClass"    $System.obj= $System.OBJ.New(clsName)

0
Robert Barbiaux · Apr 11, 2024

You can use $classmethod to invoke any class method, including %New, e.g. 

set cls = "MyPackage.MyClass"set obj = $classmethod(cls,"%New")
0