Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an interface from an object created from a TClass?

I need that some of my form classes implement the same function.

(I've discarded the idea of adding this function to a common anchestor form because I don't want to add a function which would be useless on most of my forms.)

So... I thought about using interfaces.

IMyInterface = interface
  procedure ShowHello();
end;

var  
  MyForm : TMyForm;
  MyInterface : IMyInterface;
begin
  MyForm := TMyForm.Create(Self);
  MyInterface := MyForm;
  //...
end;

In simple cases like this, it works without errors, but my application uses dynamic packages and I'm using "GetClass" function in order to obtain form classes. I tried as follows:

var
  MyForm : TForm;
  MyInterface : IMyInterface;
begin
  MyForm := TForm(GetClass('TMyForm').Create());
  MyInterface := MyForm;
end;

It causes "Incompatible types: 'IMyInterface' and 'TForm'" error. Is there a way to achieve my goal using interfaces or it would be better to try other ways?

like image 505
Fabrizio Avatar asked Aug 19 '16 14:08

Fabrizio


People also ask

Can you create an instance of an interface using its constructor?

No, you cannot have a constructor within an interface in Java. You can have only public, static, final variables and, public, abstract, methods as of Java7. From Java8 onwards interfaces allow default methods and static methods. From Java9 onwards interfaces allow private and private static methods.

What is a interface in typescript?

An interface is a syntactical contract that an entity should conform to. In other words, an interface defines the syntax that any entity must adhere to. Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members.

Does JS have an interface?

Though JavaScript does not have the interface type, it is often times needed.

What is an interface in oops?

An interface is a description of the actions that an object can do... for example when you flip a light switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have in order to be an "X".


1 Answers

Use the Supports function to check whether an interface is implemented or not.

Sample:

var
  MyForm : TForm;
  MyInterface : IMyInterface;
begin
  MyForm := TFormClass(GetClass('TMyForm')).Create(...);

  if Supports(MyForm, IMyInterface, MyInterface) then
  begin
    MyInterface.ShowHello;
  end;
end;

You need to declare GUIDs for your interfaces. Otherwise Supports doesn't work. So the interface declaration should look like this:

IMyInterface = interface
  ['{052E7D55-B633-4256-9084-37D797B01BB4}']
  procedure ShowHello();
end;
like image 177
Wosi Avatar answered Oct 24 '22 08:10

Wosi