01. THE ANATOMY
In Delphi, an Attribute is a class. It is not a special keyword; it's an object instantiated at runtime by the RTTI system.
-
A.
Must descend from
TCustomAttribute. -
B.
Applied using square brackets
[ ... ]. - C. Constructor arguments must be Constant Expressions (Integers, Strings, Sets, TypeInfo).
HOVER FOR DETAILS
type
TJsonNameAttribute = class(TCustomAttribute)
TJsonNameAttribute = class(TCustomAttribute)
// Applying it to a field
[JsonName('customer_id')]
property ID: Integer ...;
Maps to Constructor
02. THE LIFECYCLE
Attributes are "Passive". They sit in the binary until someone wakes them up. This diagram illustrates the journey from code to runtime usage.
COMPILE TIME
RUNTIME (RTTI)
EXECUTION
03. ABILITIES & TARGETS
Where to apply?
📦
Types/Classes
ƒ(x)
Methods
🏷️
Fields
⚙️
Properties
📥
Parameters
🚫
Variables
Attribute Use-Case Profiler
04. PATTERN VAULT
Serialization
CommonMapping internal field names to external JSON/XML keys.
[JsonName('user_id')]
FUserID: Integer;
// Reader logic:
if Attr is TJsonName then
Key := TJsonName(Attr).Name;
FUserID: Integer;
// Reader logic:
if Attr is TJsonName then
Key := TJsonName(Attr).Name;
Validation
LogicDefining constraints on properties for generic validator engines.
[Range(1, 100)]
property Age: Integer;
// Validator logic:
if (Val < Attr.Min) then Error;
property Age: Integer;
// Validator logic:
if (Val < Attr.Min) then Error;
AOP (Active)
AdvancedUsing TVirtualInterface to intercept calls based on attributes.
[Transaction]
procedure Save;
// InvokeHandler logic:
if Method.HasAttr(Transaction)
StartTransaction;
procedure Save;
// InvokeHandler logic:
if Method.HasAttr(Transaction)
StartTransaction;