reflection.monkey2 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. Namespace reflection
  2. #Import "<std>"
  3. Using std..
  4. #rem monkeydoc Debug reflected types.
  5. Prints all reflected types and decls.
  6. #end
  7. Function DebugTypes()
  8. For Local type:=Eachin TypeInfo.GetTypes()
  9. Print type
  10. For Local decl:=Eachin type.GetDecls()
  11. Print " "+decl
  12. Next
  13. Print ""
  14. Next
  15. End
  16. #rem monkeydoc Gets type extensions for a given type.
  17. Returns an array containing all type extensions for a given type.
  18. #end
  19. Function GetTypeExtensions:TypeInfo[]( type:TypeInfo )
  20. Global _typeExts:StringMap<TypeInfo[]>
  21. If Not _typeExts
  22. Local typeExts:=New StringMap<Stack<TypeInfo>>
  23. For Local type:=Eachin TypeInfo.GetTypes()
  24. If Not type.Kind.EndsWith( " Extension" ) Continue
  25. If Not typeExts.Contains( type.SuperType ) typeExts[type.SuperType]=New Stack<TypeInfo>
  26. typeExts[type.SuperType].Add( type )
  27. Next
  28. _typeExts=New StringMap<TypeInfo[]>
  29. For Local it:=Eachin typeExts
  30. _typeExts[it.Key]=it.Value.ToArray()
  31. Next
  32. Endif
  33. Return _typeExts[type]
  34. End
  35. #rem monkeydoc Gets the value of a property.
  36. #end
  37. Function GetProperty:Variant( name:String,instance:Variant )
  38. Local type:=instance.Type
  39. While type
  40. Local decl:=type.GetDecl( name )
  41. If decl And decl.Kind="Property" And decl.Name=name Return decl.Get( instance )
  42. For Local type:=Eachin GetTypeExtensions( type )
  43. Local decl:=type.GetDecl( name )
  44. If decl And decl.Kind="Property" And decl.Name=name Return decl.Get( instance )
  45. Next
  46. type=type.SuperType
  47. Wend
  48. Return Null
  49. End
  50. Function GetProperty<T>:T( name:String,instance:Variant )
  51. Local value:=GetProperty( name,instance )
  52. If value Return Cast<T>( value )
  53. Return Null
  54. End
  55. #rem monkeydoc Sets a property to a value.
  56. #end
  57. Function SetProperty:Bool( name:String,instance:Variant,value:Variant )
  58. Local type:=instance.Type
  59. While type
  60. Local decl:=type.GetDecl( name )
  61. If decl And decl.Kind="Property" And decl.Name=name
  62. decl.Set( instance,value )
  63. Return True
  64. Endif
  65. For Local type:=Eachin GetTypeExtensions( type )
  66. Local decl:=type.GetDecl( name )
  67. If decl And decl.Kind="Property" And decl.Name=name
  68. decl.Set( instance,value )
  69. Return True
  70. Endif
  71. Next
  72. type=type.SuperType
  73. Wend
  74. Return False
  75. End