[chuck-users] determining the type of an Object in code

mike clemow gelfmuse at gmail.com
Tue Feb 10 21:50:45 EST 2009

Hello, fellow Chuckers!

I keep finding myself returning to this issue of trying to determine
the class of an object instance at runtime.  We talked about it here:


I recently pulled from CVS and started fooling around and discovered a
remarkably simple hack.  There's a method in Object, toString(), which
returns a string containing the class of the object as well as the
reference ID.  Like this (supposing a class called "Test"):


There's also a stub in chuck_lang.cpp for a method getType(), which
isn't implemented (yet).  So, I copied the implementation of
toString(), minus the printing of the reference ID, and placed it
where the implementation of getType() should be.  Now all objects (not
UGens yet, although that would be sweet) respond to getType().


class Test {
        5 => int i;
        fun void sayHi() {
                <<< "hi" >>>;

Test test;
test @=> Object o;

// Object still knows it's a Test!
<<< o.toString() >>>;
<<< o.getType() >>>;

// Object can't sayHi()

// but this is now possible
if( o.getType() == "Test" ) {
        (o $ Test).sayHi();

The above code will print this:

"Test:11cf160" : (string)
"Test" : (string)
"hi" : (string)

This makes me very happy and opens up many doors, although I have no
idea what getType() was originally intended to do--I assume a similar
purpose.  I'm sure that this will work as a mod to the current release
as well, although I made my changes in the CVS version (I'm excited
for FileIO).

This ought to make implementing things like ArrayList a lot easier.  ;-)

I consider this a feature request (for this or something like it).  I
think this would be super helpful for UGens and primitives also.
Primitives, however, don't support the dot notation...  Oh well.  I'll
take what I can get.



More information about the chuck-users mailing list