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?
DefineClassName( MyClass ); Finally to Get the class name you'd do the following: ClassName< MyClass >::name();
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With