Get type from string
Adam D. Ruppe via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Oct 28 10:42:57 PDT 2015
On Wednesday, 28 October 2015 at 17:38:45 UTC, DarkRiDDeR wrote:
> string name = "Bob";
> __traits(getMember, Types.getType(name), "print")();
>
> How can you implement "Types.getType(name)"? I do not know in
> advance what can be the class names.
You don't. __traits works at compile time, the string isn't known
until run time.
If you can rewrite it to use an interface, you can make that work
though.
interface Printable {
void print();
}
class Bob : Printable {
void print() { writeln("hey"); }
}
void main() {
string name = "test.Bob"; // module name needed
Printable printable = cast(Printable) Object.factory(name);
if(printable is null) throw new Exception("bad class");
printable.print();
}
Object.factory's neck is on the chopping block, but it might
stick around anyway, and even if it goes away there will be an
alternative. You could register classes in your own code, for
example.
Regardless, this is a solution for now.
More information about the Digitalmars-d-learn
mailing list