About Monkey 2 › Forums › Monkey 2 Programming Help › Reflections on Reflection
Tagged: reflection
This topic contains 3 replies, has 2 voices, and was last updated by
Mark Sibly
1 year, 7 months ago.
-
AuthorPosts
-
September 17, 2017 at 7:53 am #10572
I’m trying to get the value of a DeclInfo object as a String.
The Get() method returns a Variant. I’m trying to cast the variant, but it keeps failing. What do I have to do to cast a Variant? In the code below, I tried a case-by-case casting, but that still doesn’t work:
Monkey12345678910111213141516171819202122232425Method List()Local info :TypeInfo = Self.InstanceTypePrint info.Name 'class nameFor Local decl:DeclInfo = Eachin info.GetDecls() 'all fieldsIf( ( decl.Kind = "Field" ) Or ( decl.Kind = "Global" ) ) And decl.SettablePrint " " + decl.Name + ": " + decl.Type + " = "' + StringFromDecl( decl )EndNextEndMethod StringFromDecl:String( d:DeclInfo )Select d.Type.NameCase "Double" Return String( Cast<Double>( d.Get( d ) ) )Case "Float" Return String( Cast<Float>( d.Get( d ) ) )Case "String" Return String( Cast<String>( d.Get( d ) ) )Case "Bool" Return ( Cast<Bool>( d.Get( d ) )? "True" Else "False" )Case "Float[]" Return "[]"Case "String[]" Return "[]"EndReturn "invalid type"EndOne mo’ question:
TypeInfo.GetDecls() returns ALL decls, Public, Private, Protected, etc. Is there a way to filter only the public ones (without changing the way they’re named)?
Thanks!
September 20, 2017 at 9:03 pm #10653Answering my own questions, if anyone has the same questions:
- Where it says “d.Get( d )”, it should say “d.Get( Self )”, since we’re calling this method from the instance I’m inspecting. Duh!
- Couldn’t filter by “Public”, but there’s an undocumented DeclInfo.Kind, “Property” (docs only mention Field, Global, Method and Function). That’s actually good enough for me.
Cheers!
September 20, 2017 at 9:21 pm #10654What do you mean by failing – what error are you getting/
Can you post something buildable/runnable?
September 20, 2017 at 10:05 pm #10655Beat me to it! Yes, Kind needs to be documented (supposedly is…). Will add IsPublic, IsProtected, IsPrivate (or equivalent) too.
Monkey1234567891011121314151617181920212223242526272829303132333435#Import "<reflection>"Class CField i:IntEndFunction ToString:String( d:DeclInfo,instance:Variant )Select d.TypeCase Typeof<Int> Return String( Cast<Int>( d.Get( instance ) ) )EndReturn "<error>"EndFunction Main()Local c:=New Cc.i=100Local type:=c.InstanceTypeFor Local d:=Eachin type.GetDecls()Select d.KindCase "Field"Print d.Kind+" "+d.Name+"="+ToString( d,c )EndNextEnd -
AuthorPosts
You must be logged in to reply to this topic.