在动态调用上链接方法 [英] Chaining a method on dynamic call

查看:26
本文介绍了在动态调用上链接方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Post entity

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

我可以使用

post.getUsers().clear();

并且可以添加到它

post.getUsers().addAll(Something);

如果用于动态调用函数 getUsers,我该怎么做?我试过了

how can I do the same if use to call the function getUsers dynamically? I tried

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 链接到它上面.

I just have no idea how can I chained the clear method or the addAll on it.

推荐答案

Method.invoke 返回一个 ObjectObject 类没有clear() 方法,因此需要将返回的对象强制转换为List.

Method.invoke returns an Object and the Object class does not have a clear() method, so you need to cast the returned object into a List.

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

如果你想在一行中,它是丑陋的,但可以做到:

And if you want it in one line, it is ugly, but can be done:

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

这也有效:

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

这篇关于在动态调用上链接方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆