D有反射吗?

时间:2018-11-24 20:33:32

标签: reflection d

D是否具有反射或接近反射的任何内容,以便能够在运行时访问对象?

如果不是:

在运行时如何精确地访问或编辑对象?

例如:

bool myFunc(string status){
    switch(status){
        case "create":
            Object my_obj = new createObject();
            write("Object has been created or whatever");
        break;

        case "mutate":
            //Don't want to have to make a global declaration
            my_obj.attribute = "A meme";
            write("Object has been mutated or whatever");
        break;

        case "delete":
            //Don't want to have to make a global declaration
            delete();
            write("Object has been deleted or whatever");
        break;

        default:
        //blah
        break;
    }


    return true;
}



void main(){
while(true)
{String status = readln();myFunc(status);}



}

这就是我目前能想到的,请让我知道我对D的误解。

我已经浏览了dlang.org上的文档,但找不到与反射有关的东西,或者至少与Java无关。

ps,上面的代码是我当场编写的伪代码,我可以肯定由于某种原因它实际上不会编译,我只是希望通过此操作,我想访问一个对象。具体的方式对我来说很方便。

2 个答案:

答案 0 :(得分:1)

是的,D具有反射性,但是没有,它不像Java。

D的反映是以编译时构建块而不是运行时方法的形式出现的。当然,您可以自己创建运行时方法,但它不仅可以立即使用所有功能。

我实际上今天刚刚写了一件事,反射在一个方法上循环以显示其属性并让您对其进行编辑:https://twitter.com/adamdruppe/status/1066390612516179968它尚未完成,但是我将链接起来,以便您可以看到其中的一些内容:https://github.com/adamdruppe/arsd/commit/5411dd9844869909466f2091391abe091b529bf8#diff-7a88942576365ca3d7f389b766344477R6587

无论如何,我的方法是使用反射信息从简单循环中创建方法。该语言提供了两种功能__traits和is表达式来实现此目的:

https://dlang.org/spec/traits.html

https://dlang.org/spec/expression.html#IsExpression

标准库使用std.traits模块进行包装和扩展

http://dpldocs.info/experimental-docs/std.traits.html

(或者,如果您希望使用基本相同文档的官方网站,则更难以阅读/导航:https://dlang.org/phobos/std_traits.html

您可以将其与其他代码生成技术(例如模板mixin)以及传统的东西(例如接口和构造函数)结合使用,以创建运行时材料。

但在一个简单的情况下,请尝试如下操作:

import std.stdio;
import std.conv;
import std.traits;

class MyClass {
    void myMethod() {}
    int anotherMethod(int a) { return a; }

    // this is the runtime bridge function. The trick here is to do
    // a switch, just like your example, but the innards are auto-generated
    // from the compile time reflection.
    string call(string methodName, string[] args) {
        // it starts as a plain switch...
        method_switch: switch(methodName) {
            // but inside, we use a static foreach - a compile-time loop -
            // over the __traits(allMembers) magic, which gives a list of all member names
            static foreach(inspecting; __traits(allMembers, typeof(this))) {
                case inspecting: { // you can create switch cases inside these static loops
                    // for this example, I only want to use callable methods, so this
                    // static if - a compile time if statement - will filter out anything else.
                    //
                    // It is possible to do more, like plain data members, child classes, and more,
                    // but that will add a lot more code. Same basic ideas with each of them though.
                    static if(isCallable!(__traits(getMember, this, inspecting))) {
                        // after we confirm it is callable, we can get a delegate of it
                        // (same as normally doing `&member.method`) to call later.
                        auto callable = &__traits(getMember, this, inspecting);

                        // next is building the argument list. Parameters comes from the std.traits
                        // module in the standard library and gives an object representing the function's
                        // parameters. We can loop over these and set them!
                        Parameters!callable arguments;
                        foreach(i, ref arg; arguments) { // ref loop cuz we setting the arg members..
                            // so for the runtime bridge here, I took everything as strings and
                            // want to convert them to the actual method arguments. In many cases,
                            // that automatic conversion will not be possible. The next bit of magic,
                            // __traits(compiles), will take some code and return true if it successfully
                            // compiles. Using the static if block, I can turn what would be compile time
                            // errors into a runtime exception instead.
                            static if(__traits(compiles, to!(typeof(arg))(args[i])))
                                // note that to is from the stdlib again: std.conv. It converts
                                // a thing from one type to another. Here, I ask it to convert our
                                // string (args is the runtime array of strings the user passed) to
                                // whatever the type is that the method expects.
                                //
                                // Note that this might throw an exception if the string is wrong.
                                // For example, passing "lol" to a method expecting an int will throw
                                // an exception saying cannot convert string "lol" to int.
                                arg = to!(typeof(arg))(args[i]);
                            else
                                // or if the conversion didn't compile at all, it will always throw.
                                throw new Exception("method " ~ methodName ~ " not callable with this reflection code because of incompatible argument type");
                        }

                        // now that we have the arguments, time to tackle the return value.
                        // the main special case here is a void return - that is not a value
                        // and thus cannot be converted. So we do it separately.

                        // Otherwise, though, inside we just call our callable from above with
                        // the arguments from above and return the value converted to string!

                        static if(is(ReturnType!callable == void)) {
                            // it returned void, so call it and return null
                            // because the language won't let us return void
                            // directly as a string nor convert it easily.
                            callable(arguments);
                            return null;
                        } else {
                            // it returned something else, just call the function
                            // and convert it to a string
                            return to!string(callable(arguments));
                        }
                    }
                } break method_switch;
            }
            default:
                throw new Exception("no such method " ~ methodName);
        }

        assert(0); // not reached
    }
}

// and let's call them with some strings. You could also get these strings from
// the user (just btw remember to .strip them if they come from readln, otherwise
// the trailing newline character will cause a method not found exception.)
void main() {
    auto obj = new MyClass();
    writeln(obj.call("myMethod", []));
    writeln(obj.call("anotherMethod", ["5"]));
}

这可能有助于将代码复制/粘贴到网站之外,并在常规编辑器中阅读注释,因为Stack Overflow通常会使您滚动并且很难。我在评论中展示了基本思想。

一旦您编写了该反射桥函数并使其以某种方式使您满意,就可以...可以添加任意数量的方法,它将起作用!

实际上,您甚至可以使call方法在那里成为接口的一部分,并使mixin template的主体部分的定义(请参阅https://dlang.org/spec/template-mixin.html)并将其弹出到任何的课程。

class MyNewClass : Reflectable {
    mixin CallImplementation;
}

// it will now work there!

该接口使您可以从基类(在大多数情况下与Java相同)中引用它,而mixin模板使您可以将该反射提供程序复制到每个子类中,因此即使在子类上也可以提供所有方法。 Java会自动为您执行此操作,但是在D中,您确实需要在每行中添加该mixin行。没有太多麻烦,但是要考虑一些事情。 (实际上,D也可以自动执行此操作。。但是它需要对核心运行时库进行黑客攻击,因此这是一个相当高级的主题,并且仅在特殊情况下才有用(因为您必须在项目范围内使用被黑客入侵的库)。可能对您没有用,只是暗示它在那里。)

使用btw接口,您还可以向类中添加静态构造函数,以将它们注册到某个运行时关联数组或开关中,或将任何类名注册为工厂函数,并从字符串中创建它们。无需特殊的代码即可实现,这与您以前可能见过的模式相同,但是如果您需要从字符串中获取新的类对象而不是仅编辑现有对象,那就是我的入门方法。

我会留给你这些细节,让我知道这里是否有任何意义。

答案 1 :(得分:1)

D编程语言支持编译时反射,但不支持运行时反射(例如Java)。有关编译时反射的更多详细信息,请参见亚当的答案。

10年前,托马斯·库恩(ThomasKühne)编写了一个出色的程序包,名为FlectioneD(http://dsource.org/projects/flectioned),仍然是该主题的不错参考书...