gpt4 book ai didi

java - 在动态调用上链接方法

转载 作者:行者123 更新时间:2023-12-02 09:13:28 26 4
gpt4 key购买 nike

假设我在帖子实体上有一个用户列表

private List<User> users = new ArrayList<>();

我可以使用清除它

post.getUsers().clear();

并且可以添加到它

post.getUsers().addAll(Something);

如果使用动态调用函数getUsers,我该如何做同样的事情?我试过了

post.getClass().getMethod("getUsers").invoke(post).getClass().getMethod("clear").invoke(new ArrayList<>());

我也尝试过

ArrayList.class.getMethod("clear").invoke(post);

但是我得到了

WARN  o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolved [java.lang.IllegalArgumentException: object is not an instance of declaring class]

知道我该怎么做吗?

请注意,这正在起作用

post.getClass().getMethod("getUsers").invoke(post); //get the users

我只是不知道如何链接clear方法或addAll。

最佳答案

Method.invoke返回一个 Object 并且 Object 类没有 clear() 方法,因此您需要将返回的对象转换为 列表

Post post = new Post();
Method m = post.getClass().getMethod("getUsers");
List<User> users = (List<User>)m.invoke(post);
users.clear();

如果你想把它写在一行中,这很丑陋,但可以做到:

((List<User>)(post.getClass().getMethod("getUsers").invoke(post))).clear();

这也有效:

List.class.cast(post.getClass().getMethod("getUsers").invoke(post)).clear();

关于java - 在动态调用上链接方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59209426/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com