Closed Alice52 closed 3 years ago
private static final Map<Class<?>, Class<?>> wrapperPrimitiveMap = new HashMap<>(); static { wrapperPrimitiveMap.put(Boolean.class, boolean.class); wrapperPrimitiveMap.put(Byte.class, byte.class); wrapperPrimitiveMap.put(Character.class, char.class); wrapperPrimitiveMap.put(Double.class, double.class); wrapperPrimitiveMap.put(Float.class, float.class); wrapperPrimitiveMap.put(Integer.class, int.class); wrapperPrimitiveMap.put(Long.class, long.class); wrapperPrimitiveMap.put(Short.class, short.class); }
Array.newInstance(Class, length)
// T[] array = new T[]; // compile error public static <T> T[] createArray(Class<T> componentType, int length) { return (T[]) Array.newInstance(componentType, length); } // Integer[] array = CreateWithGeneric.createArray(Integer.class, 2);
Arrays.asList(array)
@SneakyThrows public static <T> List<T> createList(Class<T> componentType) { List<T> list = new ArrayList<>(); T t; if (wrapperPrimitiveMap.containsKey(componentType)) { t = null; } else { t = componentType.newInstance(); } list.add(t); return list; } // List<Person> people = CreateWithGeneric.createList(Person.class); // [Person{name='null', age=0}] @SneakyThrows public static <T> List<T> createList(Class<T> componentType, int length) { return Arrays.asList((T[]) Array.newInstance(componentType, length)); } // List<Integer> list1 = CreateWithGeneric.createList(Integer.class, 2); // [null, null]
Generic
1. basic method[5]
2. create generic array
Array.newInstance(Class, length)
3. create generic list
Arrays.asList(array)
4. create function
5. create complex object
6. create with
Generic