Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine whether a Delphi object is of a specific class and not any descendant class?

Tags:

I have these classes and a procedure:

 TParent = class(TObject);  TChild1 = class(TParent);       TChild2 = class(TParent);   Procedure DoSomething(obj:TParent); 

What I would like to do is when obj is a TParent and not a descendant raise an exception.

I thought about doing something like this:

if obj.classname = TParent.classname then raise exception.create.... 

but it seems a bit hackish (TM)

More: What i intended is to able to pass objects that shared properties/procedures in common. After more thought, the TParent Object isn't really needed at all, what i needed was an interface object shown in my answer.

like image 762
Christopher Chase Avatar asked Mar 10 '11 04:03

Christopher Chase


2 Answers

You'll probably find the following TObject class methods useful:

  • ClassType - returns the class of an object
  • ClassParent - gives the parent class of the class
  • InheritsFrom - returns if a class inherits from another class (ie, checks the entire inheritance chain). It includes the current class.

So, you could achieve what you want (descends from TParent but not TDescendant?) with something like the following code (untested, don't have Delphi at this moment):

if obj.ClassType.InheritsFrom(TParent)   and not obj.ClassType.InheritsFrom(TDescendant) then... 

Or, if I've misunderstood and you just want to see if an object is a TParent, and not any kind of descendant at all, try:

if obj.ClassType = TParent then... 

Delphi was way ahead of its time by providing access to classes via metaclasses, so rather than just checking the class name you can access an actual class object.

like image 65
David Avatar answered Oct 04 '22 13:10

David


You're on the right track, but instead of comparing classnames, it would be simpler to check the ClassType property.

if obj.ClassType = TParent then raise exception.create.... 
like image 35
Mason Wheeler Avatar answered Oct 04 '22 11:10

Mason Wheeler