Is there a way to instantiate a class by its name in delphi?

后端 未结 2 2011
青春惊慌失措
青春惊慌失措 2020-12-01 17:01

I\'d like to instantiate a class but I only have its name in a string. Is there a way?

2条回答
  •  离开以前
    2020-12-01 17:28

    When I needed to do that, I Built my own Object Factory that uses a specially subclassed TStringList, I'm currently using Delphi 7 so the string list class supports only attach a Object to a String, then I got to subclass TStringList to make it possible handle Class Types too, so now I can instantiate a object just passing it's class name to the factory. Works that way:

    1st - Load a Singleton Object Factory;
    2st - Register any object to the factory, could be in the initialization section of the unit;

    The main Factory's methods could be: isClassRegistered, registerClass, instantiateClass(ClassName: STring): TObject;

    This way I can instantiate any object, or use a previous instantiated object, or even, a subset of they.

    I rather use a Enumerated type instead of a string to identify a Class.

    Remarks: It's a very, very terse example, a completely functional code is more complex, but, belive me, not too much.

提交回复
热议问题