Getting a class' name, but not fully qualified?

w0rp devw0rp at gmail.com
Fri Mar 28 06:42:42 PDT 2014


You could do the following.

class Klass {
     static class SubKlass {
     }
}

string baseName(ClassInfo classinfo) {
     import std.array;
     import std.algorithm : countUntil;
     import std.range : retro;

     string qualName = classinfo.name;

     size_t dotIndex = qualName.retro.countUntil('.');

     if (dotIndex < 0) {
         return qualName;
     }

     return qualName[$ - dotIndex .. $];
}

string classBaseName(Object instance) {
     if (instance is null) {
         return "null";
     }

     return instance.classinfo.baseName;
}

void main(string[] argv) {
     import std.stdio;

     writeln(Klass.classinfo.baseName);
     writeln(Klass.SubKlass.classinfo.baseName);

     Object x = new Klass();
     Object y = new Klass.SubKlass();

     writeln(x.classBaseName);
     writeln(y.classBaseName);
}

The above won't result in any extra allocation and there are two 
functions so you could find a class name both at compile time and 
a runtime without too much trouble.


More information about the Digitalmars-d-learn mailing list