Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that returns class name in D

Tags:

java

d

Say, classes A1,A2,...,An all extends the abstract class B. I would like A1,...,An to have a function that returns a string of the class name. This is certainly known in compile-time, but I would like to implement this function in B, and use inheritance so that all Ai:s get this functionality.

In java, this can easily be done, by letting B have the method

String getName() {
    return this.getClass();
}

more or less. So, how do I do this in D? Also, is there a way, using traits or similar, to determine which class members are public?

like image 329
Per Alexandersson Avatar asked Jun 22 '11 18:06

Per Alexandersson


People also ask

How do I return a class name in C++?

DefineClassName( MyClass ); Finally to Get the class name you'd do the following: ClassName< MyClass >::name();

How do you return a class name in Java?

The simplest way is to call the getClass() method that returns the class's name or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() , which returns the simple name (as in source code) and canonical name of the underlying class, respectively.

Can a return type be a class name?

When a method uses a class name as its return type, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.

How do you return a class name in Python?

In Python, use the type(object) function to return a type object. To access the classname of the type of the object, use the __name__ attribute.


2 Answers

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

like image 71
ratchet freak Avatar answered Sep 21 '22 22:09

ratchet freak


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);
}
like image 39
jcao219 Avatar answered Sep 21 '22 22:09

jcao219