ClpExampleExplorer.pas 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. unit ClpExampleExplorer;
  2. interface
  3. type
  4. TExampleExplorer = class
  5. public
  6. class procedure Execute;
  7. end;
  8. implementation
  9. uses
  10. SysUtils,
  11. Rtti,
  12. TypInfo,
  13. Generics.Collections,
  14. ClpExampleBase;
  15. class procedure TExampleExplorer.Execute;
  16. var
  17. Ctx: TRttiContext;
  18. LType: TRttiType;
  19. LInst: TRttiInstanceType;
  20. LCreate: TRttiMethod;
  21. Examples: TList<TRttiInstanceType>;
  22. Option: string;
  23. I, Idx: Integer;
  24. LExample: IExample;
  25. N: Integer;
  26. begin
  27. Examples := TList<TRttiInstanceType>.Create;
  28. try
  29. Ctx := TRttiContext.Create;
  30. for LType in Ctx.GetTypes do
  31. begin
  32. if LType is TRttiInstanceType then
  33. begin
  34. LInst := TRttiInstanceType(LType);
  35. if (LInst.MetaclassType <> nil) and LInst.MetaclassType.InheritsFrom(TExampleBase)
  36. and (LInst.MetaclassType <> TExampleBase) then
  37. begin
  38. LCreate := LInst.GetMethod('Create');
  39. if (LCreate <> nil) and (Length(LCreate.GetParameters) = 0) then
  40. Examples.Add(LInst);
  41. end;
  42. end;
  43. end;
  44. if Examples.Count = 0 then
  45. begin
  46. Writeln('No example classes found.');
  47. Exit;
  48. end;
  49. while True do
  50. begin
  51. Writeln('Choose an example to run (type exit/quit to leave):');
  52. for N := 0 to Examples.Count - 1 do
  53. Writeln(Format(' %d: %s', [N, Examples[N].Name]));
  54. Readln(Option);
  55. if SameText(Trim(Option), 'exit') or SameText(Trim(Option), 'quit') then
  56. Break;
  57. if not TryStrToInt(Trim(Option), I) or (I < 0) or (I >= Examples.Count) then
  58. begin
  59. Writeln('Invalid option. Enter a number between 0 and ', Examples.Count - 1, '.');
  60. Continue;
  61. end;
  62. Idx := I;
  63. try
  64. LCreate := Examples[Idx].GetMethod('Create');
  65. if (LCreate <> nil) and Supports(LCreate.Invoke(Examples[Idx].MetaclassType, []).AsObject, IExample, LExample) then
  66. begin
  67. try
  68. LExample.Run;
  69. finally
  70. LExample := nil;
  71. end;
  72. end;
  73. except
  74. on E: Exception do
  75. Writeln(E.ClassName, ': ', E.Message);
  76. end;
  77. end;
  78. finally
  79. Examples.Free;
  80. end;
  81. end;
  82. end.