#2875 Object Introspection

Nick Sat 27 Aug 2022

Hello All,

What is the best way to do object introspection? Trying to see for certain types what fields and methods are available without going back to the documentation. Mostly as I'm learning using fansh I find doing this to be very helpful.

Best, Nick

brian Sat 27 Aug 2022

Reflection APIS include:

Examples from the shell:

// create str  
fansh> s := "hello"

// dump all the methods in sorted order
fansh> s.typeof.methods.dup.sort.join(", ") { it.name }

// dump doc for a given method
fansh> s.typeof.method("justl").doc

// dump return/params for a given method
fansh> s.typeof.method("replace").signature

Nick Sun 28 Aug 2022

Thanks Brian. That was super helpful. I wasn't thinking about looking on the type for those tools but that makes sense in retrospect. Did lead me to an interesting behavior that I don't quite understand. I have this:

// Exploring fantom directory so assign it to a variable
fansh> e := Env.cur.homeDir

// Make an empty list
fansh> l := [,]

// Add only directories to the list
fansh> e.walk { if (it.isDir) {l.add(it)}}

// Assign first file to a var
fansh> f1 := l[1]

// It is a file
fansh> f1.typeof

// Verify it has isDir method
fansh> f1.typeof.methods.each {if (it.name.contains("isDir")) {echo(it)}}

// Use isDir method
fansh> f1.isDir
ERROR(8): Unknown slot 'sys::Obj.isDir'

The fact that I don't understand this behavior tells me I haven't yet formed a sound model of how the objects and typing system are working. Would you be able to provide some insight into why I am seeing this behavior?

Thanks, Nick

brian Sun 28 Aug 2022

There are two different types:

  • the type of the variable which is f1 - this is a Obj
  • the type of the value which LocalFile

When you call f1 you are using the type of the variable, not the value - this is the premise of static typing. You can run the scope command to see your variable types. The reason f1 got that type was thru type inference. If you change this line to the proper static type, then it would work like you expect:

l := File[,]

gulshan212 Wed 12 Apr 2023

Hello this is Gulshan Negi Well, in a programming language, object introspection is a useful method for examining objects' properties and methods. Utilizing built-in functions like dir() and type(), the inspect module, and text editor and IDE-provided tools are all ways to carry out object introspection. The best approach will be determined by the language and development environment that are being used, so it's important to look into all of your options and choose the methods that are most effective for your workflow. I hope you are clear now. Thanks

Login or Signup to reply.