我有一些用于测试的辅助类,结构如下:
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/