这个错误是什么意思?java.lang.reflect.InaccessibleObjectException:无法将字段设为私有final int java.time.LocalDate.year

28 java jackson java-time

我正在尝试创建一种方法,该方法使用 Json 数据和 jackson 库来获取对象列表。如果我运行我的代码,我会收到错误:

java.lang.reflect.InaccessibleObjectException:无法使字段私有final int java.time.LocalDate.year可访问:模块java.base不会“打开java.time”到未命名模块@5c90e579

即使我的代码中有 JodaModul,为什么它会给我一个关于 LocalDate 的错误?

public static List<Tweet> getTweetsFile() throws Exception{

            ObjectMapper mapper = new ObjectMapper().
                    registerModule(new JodaModule()).
                    configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            
            File path = new File ("C:/Users/PC/eclipse-workspace/hw4/tw.json");

            List<Tweet> myObjects3 =  Arrays.asList(mapper.readValue(path, Tweet.class));
    
            return myObjects3;
    }
Run Code Online (Sandbox Code Playgroud)

它在我的文件中的样子:

[{"date":"2001-12-28","tweetNumber":1,"country":"England","comments":11,"message":"I like to watch anime and reading books","retweets":3,"username":"Isabelle","likes":55},{"date":"2003-05-11","tweetNumber":2,"country":"France","comments":25,"message":"I'm Viatnamese, but I live in France","retweets":30,"username":"Vin","likes":110}..
Run Code Online (Sandbox Code Playgroud)

它的顺序不正确,就像我的对象在其构造函数中的顺序一样,这可能是原因吗?

mak*_*son 32

您可以自行解决此问题。

添加--add-opens java.base/java.time=ALL-UNNAMED作为开始参数,它会起作用。

这是对应的JEP


小智 7

我用这种方法解决了这个问题。首先,您必须使用 Json 数据中给定的日期格式创建 LocalDateTime 反序列化器。

class LocalDateTimeDeserializer implements JsonDeserializer < LocalDateTime > {
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
    return LocalDateTime.parse(json.getAsString(),
        DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss").withLocale(Locale.ENGLISH));
}
Run Code Online (Sandbox Code Playgroud)

}

然后创建 GsonBuilder 类型的对象并使用 LocalDateDeserializer 对其进行调整。

gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer());

Gson gson = gsonBuilder.setPrettyPrinting().create();
Run Code Online (Sandbox Code Playgroud)


小智 6

在 STS 或 eclipse 中,在默认 VM 参数中添加以下语句

--add-opens java.base/java.time=ALL-UNNAMED

默认 VM 参数路径:窗口 -> 首选项 -> 安装的 JRE -> 选择 jre -> 编辑


小智 -11

我把jdk16改成jdk11解决了这个问题。

  • 你还没有解决它。您刚刚推迟了这个问题,以便当您迁移到 Java 17(或更高版本)时它会回来咬您。 (6认同)