Java中如何初始化Instant类型?实例化失败问题求助
搞定Instant初始化问题,顺便适配你的Freemarker代码
嘿,你踩的这个坑我之前也遇到过——Java里的Instant类根本没有公共的无参构造器,它的构造器是私有的,所以直接写new Instant()肯定会报错。毕竟Instant是Java 8日期时间API里的不可变类,必须用它提供的静态工厂方法来创建实例。
正确创建Instant实例的几种方式
根据你后续Freemarker代码里要用到的ofEpochSecond,其实你根本不需要单独去“初始化”一个Instant对象,因为ofEpochSecond本身就是静态方法,直接通过类名调用就行。不过还是给你列几个常用的创建方式:
获取当前系统时间的Instant:
Instant now = Instant.now();通过秒级时间戳创建(就是你Freemarker里要用到的场景):
// 替换成你的data.time.seconds对应的数值,注意是long类型 Instant instant = Instant.ofEpochSecond(1680000000L);通过毫秒级时间戳创建:
Instant instant = Instant.ofEpochMilli(System.currentTimeMillis());
Freemarker代码的修正建议
看你给出的这段Freemarker代码:
[#assign dateFormated = newDate.from(instant.ofEpochSecond(data.time.seconds))/]
这里有个小问题:instant.ofEpochSecond应该改成Instant.ofEpochSecond(用类名调用静态方法),因为在Freemarker里调用Java类的静态方法,要么提前导入类,要么用全类名。
给你两种修正方案:
- 用全类名调用(最稳妥,不用额外配置):
[#assign dateFormated = newDate.from(java.time.Instant.ofEpochSecond(data.time.seconds))/] - 如果你已经在Freemarker的配置里导入了
java.time.Instant类,就可以简化成:[#assign dateFormated = newDate.from(Instant.ofEpochSecond(data.time.seconds))/]
额外小提示
要是你是在Java代码里提前准备好Instant对象再传给Freemarker模板,那直接用静态方法创建后丢进模板上下文就行,比如:
// Java层创建Instant实例 Instant instant = Instant.ofEpochSecond(data.getTime().getSeconds()); // 把实例放到Freemarker的模型里 templateModel.put("instant", instant);
然后在模板里就能直接用${instant}或者配合其他方法使用,但看你的需求是直接在模板里通过秒数生成,所以前面的静态方法调用方式更适合你。
内容的提问来源于stack exchange,提问作者Tonino Fernandez
相关产品推荐
相关产品推荐

