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.
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/p/17069179.html