主要是简化代码。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author lyu
* @description:
* @create 2024-09-14 16:31
*/
public class MapUtils {
private MapUtils() {
throw new UnsupportedOperationException("Disable creation of instance objects through reflection");
}
public static <K, V> Map<K, V> of(K k1, V v1) {
Map<K, V> map = new HashMap<>();
map.put(k1, v1);
return map;
}
public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2) {
Map<K, V> map = of(k1, v1);
map.put(k2, v2);
return map;
}
public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
Map<K, V> map = of(k1, v1, k2, v2);
map.put(k3, v3);
return map;
}
public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
Map<K, V> map = of(k1, v1, k2, v2, k3, v3);
map.put(k4, v4);
return map;
}
public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
Map<K, V> map = of(k1, v1, k2, v2, k3, v3, k4, v4);
map.put(k5, v5);
return map;
}
/**
* 建造者
* @param <K> key class
* @param <V> value class
*/
public static class Builder<K, V> {
public static class KeyValue<K, V> {
private final K key;
private final V value;
public KeyValue(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
private final List<KeyValue<K, V>> element = new ArrayList<>();
public Builder<K, V> keyValue(K k, V v) {
element.add(new KeyValue<>(k, v));
// 链式调用
return this;
}
public Map<K, V> build() {
Map<K, V> map = new HashMap<>();
element.forEach(elm -> map.put(elm.getKey(), elm.getValue()));
element.clear();
return map;
}
}
}
使用方式
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;
/**
* @author lyu
* @description:
* @create 2024-09-14 16:52
*/
public class Main {
@Test
public void test1(){
System.out.println(MapUtils.of("k", "v", "k2", "c","k3", "c","k4", "c"));
}
@Test
public void test2(){
Map<String, Integer> map = new MapUtils.Builder<String, Integer>()
.keyValue("one", 1)
.keyValue("two", 2)
.keyValue("three", 3)
.keyValue("12",2)
.keyValue("qwe",23)
.build();
System.out.println(map);
}
@Test
public void test3(){
Map<String, Date> map = new MapUtils.Builder<String, Date>()
.keyValue("one", new Date())
.keyValue("two", new Date())
.build();
System.out.println(map);
}
@Test
public void refection() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class<MapUtils> clazz = MapUtils.class;
// 获取无参构造函数
Constructor<?> constructor = clazz.getDeclaredConstructor();
//禁用安全检查
constructor.setAccessible(true);
// 创建对象
Object person = constructor.newInstance();
System.out.println(person);
}
其中注意的一点是 MapUtils 构造方法是私有的,但是可通过反射去创建对象了,违反了工具类的设计初衷,那么可以在私有构造方法中抛出异常,那么通过反射也是不能创建对象的!
标签:Map,map,创建,v1,k1,工具,k2,public From: https://www.cnblogs.com/lyuSky/p/18414402