www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Get type from string

reply DarkRiDDeR <DarkRiDDeRr ya.ru> writes:
Example:

class Bob {
  static void print ()
  {
    write("str");
  }
}
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.
Oct 28 2015
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
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.
Oct 28 2015
parent reply DarkRiDDeR <DarkRiDDeRr ya.ru> writes:
Thank you! Is it possible to call a method from a string at run 
time?
Oct 28 2015
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Wednesday, 28 October 2015 at 17:57:16 UTC, DarkRiDDeR wrote:
 Thank you! Is it possible to call a method from a string at run 
 time?
Yes, though you have to prepare code to do it. Again, I'd try to make it work on interfaces on some level. The free sample chapter of my book https://www.packtpub.com/application-development/d-cookbook shows an example near the end of how to write that code. Basically, you loop over members at compile time and generate wrapper functions for them, which you then call based on a runtime string.
Oct 28 2015
parent DarkRiDDeR <DarkRiDDeRr ya.ru> writes:
On Wednesday, 28 October 2015 at 20:04:51 UTC, Adam D. Ruppe 
wrote:
 On Wednesday, 28 October 2015 at 17:57:16 UTC, DarkRiDDeR wrote:
 Thank you! Is it possible to call a method from a string at 
 run time?
Yes, though you have to prepare code to do it. Again, I'd try to make it work on interfaces on some level. The free sample chapter of my book https://www.packtpub.com/application-development/d-cookbook shows an example near the end of how to write that code. Basically, you loop over members at compile time and generate wrapper functions for them, which you then call based on a runtime string.
I had the same idea to solve this problem. But the book is already good examples. Thank you.
Oct 29 2015