我正在尝试对Map
对象中的每个条目执行映射操作.
我需要从键中取一个前缀并将值从一种类型转换为另一种类型.我的代码从a获取配置条目Map<String, String>
并转换为a Map<String, AttributeType>
(AttributeType
只是一个包含一些信息的类.进一步的解释与此问题无关.)
我能够使用Java 8 Streams获得的最佳结果如下:
private Map<String, AttributeType> mapConfig(Map<String, String> input, String prefix) {
int subLength = prefix.length();
return input.entrySet().stream().flatMap((Map.Entry<String, Object> e) -> {
HashMap<String, AttributeType> r = new HashMap<>();
r.put(e.getKey().substring(subLength), AttributeType.GetByName(e.getValue()));
return r.entrySet().stream();
}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
Run Code Online (Sandbox Code Playgroud)
Map.Entry
由于它是一个接口而无法构造,导致单个条目Map
实例的创建和使用flatMap()
,这看起来很难看.
还有更好的选择吗?使用for循环似乎更好:
private Map<String, AttributeType> mapConfig(Map<String, String> input, String prefix) {
Map<String, AttributeType> result = new HashMap<>();
int subLength = prefix.length();
for(Map.Entry<String, String> entry : input.entrySet()) {
result.put(entry.getKey().substring(subLength), …
Run Code Online (Sandbox Code Playgroud) 我们有一个可以使用groovy脚本进行自定义的系统,我发现这些脚本抛出的异常类型有一个非常奇怪的影响.
我们有一个groovy脚本,包含以下内容:
process {
throw new Exception("weeee")
}
Run Code Online (Sandbox Code Playgroud)
进程被定义为脚本基类中的Closure:
public abstract class ScriptBaseClass extends Script {
Closure process;
public void process( Closure code ) {
process = (Closure) code.clone();
}
}
Run Code Online (Sandbox Code Playgroud)
在实际运行脚本的Java类中,我们有以下方法(省略了所有设置代码,因为它似乎不相关):
public void process() {
try {
script.process.call();
} catch (Exception e) {
logger.debug("exception thrown from groovy script", e);
throw e;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,此处的处理方法不会声明它会抛出任何异常.然而,很明显它重新抛出了它捕获的异常e.这段代码是有效的,它编译和运行非常愉快.它按我的意愿抛出异常.
有谁知道这是合法代码?从理论上讲,我不应该从一个没有声明它抛出它的方法中抛出一个已检查的异常.
如果一个类扩展了一个 Map 并包含一些额外的字段。EG 最后修改日期,Jackson 似乎忽略了任何未包含为地图属性的内容。
我有一个看起来像下面这样的类:
import java.io.IOException;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Objects;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Foo extends HashMap<String, String> {
private OffsetDateTime lastModifiedTime;
public Foo() {
super();
lastModifiedTime = OffsetDateTime.now();
}
public void setLastModifiedTime(OffsetDateTime newTime) {
this.lastModifiedTime = newTime;
}
public OffsetDateTime getLastModifiedTime() {
return this.lastModifiedTime;
}
public static void main(String[] args) throws IOException {
Foo f = new Foo();
f.put("hello", "world");
ObjectMapper om = new ObjectMapper();
om.findAndRegisterModules();
String result = om.writeValueAsString(f);
if(f.equals(om.readValue(result, Foo.class))) {
System.out.println("Wooo");
} …
Run Code Online (Sandbox Code Playgroud)