当方法具有变量 arglist 时的 Java 反射

发布于 2024-12-20 05:47:24 字数 710 浏览 2 评论 0原文

我有一些类似于以下内容的内容:

public class A { 
    public void theMethod(Object arg1) {
        // do some stuff with a single argument
    }
}

public class B {
    public void reflectingMethod(Object arg) {
        Method method = A.class.getMethod("theMethod", Object.class);
        method.invoke(new A(), arg);
    }
}

如何修改它以便我可以执行以下操作?

public class A { 
    public void theMethod(Object... args) {
        // do some stuff with a list of arguments
    }
}

public class B {
    public void reflectingMethod(Object... args) {
        Method method = A.class.getMethod("theMethod", /* what goes here ? */);
        method.invoke(new A(), args);
    }
}

I've got something along the lines of the following:

public class A { 
    public void theMethod(Object arg1) {
        // do some stuff with a single argument
    }
}

public class B {
    public void reflectingMethod(Object arg) {
        Method method = A.class.getMethod("theMethod", Object.class);
        method.invoke(new A(), arg);
    }
}

How do I modify that so that I can do the following instead?

public class A { 
    public void theMethod(Object... args) {
        // do some stuff with a list of arguments
    }
}

public class B {
    public void reflectingMethod(Object... args) {
        Method method = A.class.getMethod("theMethod", /* what goes here ? */);
        method.invoke(new A(), args);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何以笙箫默 2024-12-27 05:47:24
A.class.getMethod("theMethod", Object[].class);
A.class.getMethod("theMethod", Object[].class);
月棠 2024-12-27 05:47:24

一旦我开始思考如何做到这一点,达尼纽斯在原始问题评论中的建议就奏效了。

public class A {
    public void theMethod(ArrayList<Object> args) { // do stuff 
    }
}

public class B {
    public void reflectingMethod(ArrayList<Object> args) {
        Method method;
        try {
            method = A.class.getMethod("theMethod", args.getClass());
            method.invoke(new A(), args);
        } catch (Exception e) {}
    }
}

Darthenius's suggestion in the comments for the original question worked, once I wrapped my head around how to do it.

public class A {
    public void theMethod(ArrayList<Object> args) { // do stuff 
    }
}

public class B {
    public void reflectingMethod(ArrayList<Object> args) {
        Method method;
        try {
            method = A.class.getMethod("theMethod", args.getClass());
            method.invoke(new A(), args);
        } catch (Exception e) {}
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文