Alice52 / java-ocean

java-tutorial .We intend to explain Java knowledge in this repository.
MIT License
0 stars 0 forks source link

[reflect] create object #136

Closed Alice52 closed 3 years ago

Alice52 commented 4 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);
}

1. basic method[5]

  1. new
  2. Class.newInstance
  3. Constructor.newInstance
  4. Clone 方法
  5. 反序列化

2. create generic array

  1. 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);

3. create generic list

  1. 创建一个普通对象 + add to list
  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]

4. create function

5. create complex object

6. create with Generic

  1. reference
Alice52 commented 3 years ago

generic erasure

  1. instanceof T; // Error
  2. new T(); // Error
  3. new T[10]; // Error

suggestion

  1. pass T
  2. and pass Class for type
Alice52 commented 3 years ago

notice

  1. it's bad thinking to clear T type, please pass Class as args
  2. the Subtle of Generic is no type, so donot try clear T type