My question is how to access a class which is in an other unit? For an example:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils,
Classes,
System,
StrUtils,
Math,
TypInfo,
Data in 'Data.pas';
var
Str, name, value : string;
List, tmpList : TStringList;
i : Integer;
Obj : TObject;
CRef : TPersistentClass;
d : TData;
begin
d := TData(GetClass('Data.TData').Create);
Writeln(Format('%s', [d.Name]));
Readln;
Readln;
end.
And the Data unit :
unit Data;
interface
uses
SysUtils,
Classes;
type
TData = class(TObject)
FName : string;
published
property Name : string read FName write FName;
end;
type
TIn = class(TObject)
FName : string;
published
property Name : string read FName write FName;
end;
implementation
end.
The problem is that the method GetClass return me always nil. I know that there is a questions like this one but they doesn't helped me.
Thanks in advance!
If you are using one of the later Delphi versions you can use the RTTI unit.
In your example TIn is not a inner class, but inner classes can also be accessed like this:
Given that d is defined as
TData
, can't you simply used := TData.Create()
?Anyway if you want to create class from its name, you have to (look this link) call
RegisterClass
before usingGetClass
or that class won't be recognized and you get anil
.You didn't register the class. You need to call
RegisterClass
.Typically you would place a call to
RegisterClass
in the initialization section unit that declares the class.When you come to call
RegisterClass
you will discover that the class needs to derived fromTPersistent
:Please read the GetClass documentation. It only works with registered persistent classes. So The first thing you must change in order to use it is descend from TPersistent, ie
and then you have to make sure that the class is registred, ie you have to call RegisterClasses, perhaps in the initialization section of the unit