Is runtime type info possible?

Monkey Forums/Monkey Programming/Is runtime type info possible?

AaronK(Posted 2012) [#1]
Hi guys, I was wondering if Monkey has a way to take an object of a class and then check it to see if it implements an interface before invoking it.

I see there's a reflection class, but I can't see how to use it on an actual object and not a class name. Here's an idea of what I'm trying to do.


Class A
  Method Do()
End

Class B implements A
    Method Do()
    End
End

Function Yo(target:Object)
  if target implements A 
     Call target.Do()
  End
End



Alternatively, is there a way to cast?

I can obviously work around these problems but I'm looking to implement something along the lines of Cocos2d's actions which I find rather elegant and flexible.


Tibit(Posted 2012) [#2]
I think it is simpler than you think, would this work for your purpose?

[monkeycode]
Interface A
Method Do()
End

Class B implements A
Method Do()
Print "B Do"
End
End

Class C Implements A
Method Do()
Print "C Do"
End
End

Function Main()
Yo(New B)
Yo(New C)
End

Function Yo(target:Object)
Local targetA:A = A(target)
If targetA
targetA.Do()
End
End
[/monkeycode] You can test and run this.


Samah(Posted 2012) [#3]
That kind of defeats the purpose of interfaces though... if your code requires explicit casts like that, you need to rethink your design. I know this from experience :)


AaronK(Posted 2012) [#4]
Thanks Tibit, that's exactly what I wanted to know so I'll try that and see if that suffices.

Samah, I know if you come from a statically typed language background that it's not considered "right" (I've been developing in C++ commercially for about 17 years), however I've also developed in Objective C for a couple of years and feel dynamic languages like that have a lot of benefits. Of course Monkey is statically typed so what I'm trying to do is not really language friendly but I'm looking for a solution that when used for future projects and by others is simple to understand and use without creating a more complicated object hierarchy.

That said, I am looking into all options, I just wanted to know if a casting system could work.


Tibit(Posted 2012) [#5]
And yes, I agree with Samah. Myself have barley a single cast in my entire code base for all my games and frameworks.

Tough if the purpose is to convert code that does just that, I guess it is simpler to just clone it that way, make it work, and then if the desire still exists refactor the architecture.


AaronK(Posted 2012) [#6]
As an aside, Tibit how is Utoopia going? I did register with you guys some time ago and am not sure if I made it into the testing cycle or not but I haven't heard anything.