#2875 Object Introspection

Nick Sat 27 Aug

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

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

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

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[,]

Login or Signup to reply.