Is it possible to solve the “A generic array of T is created for a varargs parameter” compiler warning?

前端 未结 8 1653
Happy的楠姐
Happy的楠姐 2020-11-28 04:31

This is a simplified version of the code in question, one generic class uses another class with generic type parameters and needs to pass one of the generic types to a metho

8条回答
  •  再見小時候
    2020-11-28 05:06

    If you're after a fluent-type interface, you could try the builder pattern. Not as concise as varargs but it is type safe.

    A static generically-typed method can eliminate some of the boilerplate when using the builder, while retaining the type safety.

    The builder

    public class ArgBuilder implements Iterable {
    
        private final List args = new ArrayList();
    
        public ArgBuilder and(T arg) {
            args.add(arg);
            return this;
        }
    
        @Override
        public Iterator iterator() {
            return args.iterator();
        }
    
        public static  ArgBuilder with(T firstArgument) {
            return new ArgBuilder().and(firstArgument);
        }
    }
    

    Using it

    import static com.example.ArgBuilder.*;
    
    public class VarargsTest {
    
        public static void main(String[] args) {
            doSomething(new ArgBuilder().and("foo").and("bar").and("baz"));
            // or
            doSomething(with("foo").and("bar").and("baz"));
        }
    
        static void doSomething(Iterable args) {
            for (String arg : args) {
                System.out.println(arg);
            }
        }
    }
    

提交回复
热议问题