Generic type as parameter in Java Method

后端 未结 3 1951
醉酒成梦
醉酒成梦 2020-12-14 06:30

Do you think it is possible to create something similar to this?

private ArrayList increaseSizeArray(ArrayList array_test, GenericClass) {
    array_test.ad         


        
相关标签:
3条回答
  • 2020-12-14 07:05

    Yes, you can.

    private static <T> List<T> pushBack(List<T> list, Class<T> typeKey) throws Exception {
        list.add(typeKey.getConstructor().newInstance());
        return list;
    }
    

    Usage example:

    List<String> strings = new ArrayList<String>();
    pushBack(strings, String.class);
    
    0 讨论(0)
  • 2020-12-14 07:14

    simple solution!

    private <GenericType> ArrayList increaseSizeArray(ArrayList array_test, GenericType genericObject)
    {
        array_test.add(new genericObject());
        return ArrayList;
    }
    
    0 讨论(0)
  • 2020-12-14 07:20

    Old question but I would imagine this is the preferred way of doing it in java8+

    public <T> ArrayList<T> dynamicAdd(ArrayList<T> list, Supplier<T> supplier) {
      list.add(supplier.get());
      return list;
    }
    

    and it could be used like this:

    AtomicInteger counter = ...;
    ArrayList<Integer> list = ...;
    
    dynamicAdd(list, counter::incrementAndGet);
    

    this will add a number to the list, getting the value from AtomicInteger's incrementAndGet method

    Also possible to use constructors as method references like this: MyType::new

    0 讨论(0)
提交回复
热议问题