Like getClass()

bearophile bearophileHUGS at lycos.com
Sat Sep 27 09:15:07 PDT 2008


I'm trying to learn more about D object system (this is derived from a discussion I've had in #D), I have problems fully understanding some of the things the D docs say. This is a little Java program for reference:

// Java code
import java.util.*;
interface FooBar {}
class Foo implements FooBar {}
class Bar implements FooBar {}
public class test {
    public static void main(String[] args) {
        ArrayList<FooBar> things = new ArrayList<FooBar>();
        things.add(new Bar());
        things.add(new Foo());
        for (FooBar thing : things)
            System.out.println(thing.getClass());
    }
}
/*
Output of the Java version:
class Bar
class Foo
*/


I have tried to translate it to D, and I have failed so far, this code compiles and runs, but I'd like to see the original class names in the output:

// D code
import std.stdio;
interface FooBar {}
class Foo : FooBar {}
class Bar : FooBar {}
void main() {
    FooBar[] things;
    things ~= new Bar;
    things ~= new Foo;
    foreach (thing; things)
        writefln(typeid(typeof(thing)));
}
/*
Output of the D version:
test.FooBar
test.FooBar
*/

As you can see in D I am not able yet to find the class of the objects inserted into the 'things' array. Do you have suggestions? (I'd like to do this to sort the 'things' array according to the class).

Bye and thank you,
bearophile


More information about the Digitalmars-d-learn mailing list