rtti路由

rtti路由

复制代码
/// <author>2023-1-26</author>
unit rtti.execfunc;

interface

uses
  System.Classes, system.Rtti, System.StrUtils, System.SysUtils;

type
  /// <code>
  /// 基类
  /// </code>
  TFunc = class(TPersistent)
  end;

/// <summary>
/// 动态执行指定类的方法
/// </summary>
/// <param name="className">类名</param>
/// <param name="funcName">方法名</param>
/// <param name="funcParam">方法参数</param>
function execFunc(className, funcName: string; funcParam: array of TValue): TValue;

implementation

function FindAClass(const className: string): TClass;
var
  ctx: TRttiContext;
  typ: TRttiType;
  list: TArray<TRttiType>;
begin
  Result := nil;
  ctx := TRttiContext.Create;
  list := ctx.GetTypes;
  for typ in list do
  begin
    if typ.IsInstance and (EndsText(className, typ.Name)) then
    begin
      Result := typ.AsInstance.MetaClassType;
      break;
    end;
  end;
  ctx.Free;
end;

function execFunc(className, funcName: string; funcParam: array of TValue): TValue;
begin
  var ctx: TRttiContext;
  var t: TRttiType;
  var m: TRttiMethod;
  ctx := TRttiContext.Create;
  var c: TClass := FindAClass(className);
  if c = nil then
  begin
    Writeln('还没有注册类: RegisterClass(TFunc1)');
    Exit;
  end;
  t := ctx.GetType(c);
  m := t.GetMethod(funcName);
  var o: TFunc := c.Create as TFunc;
  Result := m.Invoke(o, funcParam);
  ctx.Free;
  o.Free;
end;

end.
复制代码

 非RTTI的:

复制代码
/// <author>2023-2-10</author> fit delphi\lazarus
unit api.router;
{$IFDEF fpc}
  {$MODE DELPHI}{$H+}
{$ENDIF}
interface

uses
  keyvalue.serialize,
  Classes, StrUtils, SysUtils;

type
  TFun = procedure (req, res: TSerialize) of object;
  /// <code>
  /// 基类
  /// </code>
  TFunc = class(TPersistent);

/// <summary>
/// 动态执行指定类的方法
/// </summary>
procedure RouterAPI(className, funcName: string; req, res: TSerialize);

implementation

procedure RouterAPI(className, funcName: string; req, res: TSerialize);
var
  m: TMethod;
  f: TFun;
  p: TPersistentClass;
begin
  p := FindClass(className);
  if p = nil then exit;
  m.Data := Pointer(p);
  m.Code := p.MethodAddress(funcName);
  if Assigned(m.Code) then
  begin
    f := TFun(m);
    f(req, res);
  end;
end;

end.
复制代码

 

posted @   delphi中间件  阅读(74)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2018-01-27 UNIGUI换版本注意事项
2015-01-27 结构体的序列和还原
点击右上角即可分享
微信分享提示