digitalmars.D.learn - Get type from string
- DarkRiDDeR (11/11) Oct 28 2015 Example:
- Adam D. Ruppe (22/26) Oct 28 2015 You don't. __traits works at compile time, the string isn't known
- DarkRiDDeR (2/2) Oct 28 2015 Thank you! Is it possible to call a method from a string at run
- Adam D. Ruppe (8/10) Oct 28 2015 Yes, though you have to prepare code to do it. Again, I'd try to
- DarkRiDDeR (4/15) Oct 29 2015 I had the same idea to solve this problem. But the book is
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
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
Thank you! Is it possible to call a method from a string at run time?
Oct 28 2015
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
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:I had the same idea to solve this problem. But the book is already good examples. Thank you.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 29 2015