![](/img/trans.png)
[英]How to define when my @Scheduled method should be called first time?
[英]How to define the map as a constant object instead of a method which will be created every time when it is called
这是我用来填充 map 的方法,将来还会添加其他数据。
public class myClass{
public Map populateMap(client: RedissonClient) {
Map map = client.getMap("map");
map.put(k1, v1);
map.put(k2, v2);
...
return map;
}
}
The problem is, each time when I calling this method in my main function, it will re-create the same map content again and again, is there a way to define it as a constant map object, not in a method.
Map map = myClass.populateMap(client);
...
从您的问题来看,尚不清楚 map 应该属于实例还是属于 class。
要创建 class 常量 map,请使用Map::of
:
class MyClass {
static final Map<String, String> MAP = Map.of("k1", "v1", "k2", "v2");
}
上述 map 是不可修改的 map :保证不会对 map 1进行任何修改。 如果你想把这个 map 的内容变成一个新的 map,为了给它添加额外的数据,只需使用
Map<String, String> newMap = new HashMap<>(MyClass.MAP);
newMap.put(...);
1好吧,也许通过反思是可能的。 但是对于反射适用:只有在您知道自己在做什么时才使用它。
如果你使用方法 static,你可以初始化一个 static map:
public class MyClass{
public static Map<String, String> map = populateMap();
private static Map<String, String> populateMap() {
Map<String, String> map = new HashMap<>();
map.put("k1", "v1");
map.put("k2", "v2");
...
return map;
}
}
现在所有其他类都可以访问填充的MyClass.map
实际上已经说过,使 map 成为全局常量,或者在 java 术语中: static 最终字段。
public class myClass {
private static final Map<String, String> MAP = new HashMap<>();
static {
MAP.put(k1, v1);
MAP.put(k2, v2);
}
或者因为 java 9 更容易完成(感谢@GhostCat):
private static final Map<String, String> MAP =
Map.of(k1, v1,
k2, v2);
使用类型,如接口Map<Integer, Object>
。 并为创建选择实施 class。
static {... }
称为static 初始化程序。
您可以将其设置为如上所述的全局变量。
public final static Map<String, String> MAP = populateMap();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.