Function that returns class name in D

simply typeof(this).stringof

however this is fixed at compile time so inheritance doesn't change the value

this.typeinfo.name

will give the dynamic name of the classname of the instance

http://www.d-programming-language.org/expression.html#typeidexpression
http://www.d-programming-language.org/phobos/object.html#TypeInfo_Class


It is known at compile-time, but evaluating the class name at runtime requires demangling, I think.

Here it is if runtime-evaluation is okay:

import std.stdio;
import std.algorithm;

abstract class B {
    string className() @property {
        return this.classinfo.name.findSplit(".")[2];
    }
}

class A1 : B { }
class A2 : B { }

void main()
{
    auto a1 = new A1();
    writeln(a1.className);

    auto a2 = new A2();
    writeln(a2.className);
}

You can get the name of a class simply by using ClassName.stringof.

If you want it as a virtual function then I would recommend using the Curiously Recurring Template Pattern:

class B
{
    abstract string getName();
}

class BImpl(T)
{
    string getName() { return T.stringof; }
}

class A1 : BImpl!A1 { ... }
class A2 : BImpl!A2 { ... }
/+ etc. +/

Unfortunately, at the moment there is no way to determine which class members are public. You can iterate all members by using the allMembers trait.

foreach (member; __traits(allMembers, MyClass))
    writeln(member);

Tags:

Java

D