java获取方法集合

标签 java collections

我有一些用于测试的辅助类,结构如下:

public class EntitiesForTest {
    public static Entity firstEntity() {
        return new Entity(/*some dummy data*/)
    }

    public static Entity secondEntity() {...}
    ...
    public static Entity nthEntity() {...}

    public static List<Entity> allEntities() {???}
}

这个类的目的是让一些对象来测试我系统的上层,比如用一些 JSON 数据来测试 REST 服务。这种技术不是我的,而是来 self 正在参加的在线类(class),非常酷。

我想知道是否有办法构造一个 List<Entity>基于类的静态继承方法和集合框架。我能做到Arrays.asList(/*call the methods one by one comma-separated*/)但必须有一种更智能、更实用且可重复使用的方法来做到这一点。

预先感谢您的回答。

最佳答案

“现代”方式

public static List<Entity> getEntities() {
    return Arrays.stream(Foo.class.getMethods()).
            filter(method -> method.getReturnType() == Entity.class && 
                             Modifier.isStatic(method.getModifiers())).
            map(method -> {
                try {
                    return (Entity)method.invoke(null);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    throw new RuntimeException(e); // exceptions in streams... lol
                }
            }).
            collect(Collectors.toList());
}

我希望我知道一种避免强制转换的方法,但我不是很清楚。

关于java获取方法集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37486872/

相关文章:

java - 如何从同一类中的另一个方法调用变量,以及调用该方法?

java - Spring beans 在 IntelliJ 中未解决

java - 为什么 Range 会抛出 UnsupportedOperationException?

Java 集合 : What collection to use is this very specific case?

java - 我什么时候使用 java Collections singletonMap 方法?

php - "prototype"的项目 "Array"不存在

java - 哈希表和 HashMap

javascript - 如何将 jade-agents (java) 和 babylon.js (html/javascript) - Servlet 连接到 html?

java - Spring MVC @RequestBody 不适用于 jquery ajax?

java - AndroidX 喷射器 : Failed to transform file 'android-all-9-robolectric-4913185-2.jar' to match attributes using transform JetifyTransform