Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the name of the method a method pointer points to?

I have defined the following :

  • a method pointer that returns 0 if a verification is OK or an error code

    TValidationFunc = Function(AParam: TAnObject): integer Of Object;
    
  • a list of functions to perform:

    Functions: TObjectList < TValidationFunc>;
    

I put several functions with this signature in my Functions list.

To execute them I perform:

For valid In Functions Do
Begin
  res := -1;
  Try
    res := valid(MyObject);
  Except
    On E: Exception Do
      Log('Error in function ??? : ' + E.Message, TNiveauLog.Error, 'PHVL');
  End;
  Result := Result And (res = 0);
End;

How can I get the name of my original function in my log, in case this function raises an exception?

like image 425
o.schwab Avatar asked Feb 21 '14 11:02

o.schwab


1 Answers

The easiest solution would be - as David hints at - to store the name along with the function pointer, like this:

TYPE
  TValidationFunc = Function(AParam: TAnObject): integer Of Object;
  TFunctions = TDictionary<TValidationFunc,String>;

VAR
  Functions : TFunctions;

populate the list:

Functions:=TFunctions.Create;
Functions.Add(Routine1,'Routine1');
Functions.Add(Routine2,'Routine2');

and then when you run through it:

For valid In Functions.Keys Do Begin
  Try
    res := valid(MyObject);
  Except
    On E: Exception Do Begin
      Log('Error in function ' + Functions[valid] + ' : ' + E.Message, TNiveauLog.Error, 'PHVL');
      res := -1;
    End;
  End;
  Result := Result And (res = 0);
End;

This way, you "link" the validation function with a name in a TDictionary, so that when you have the one, you can obtain the other.

like image 105
HeartWare Avatar answered Sep 19 '22 11:09

HeartWare