Java SafeVarargs annotation, does a standard or best practice exist?

前端 未结 2 1627
说谎
说谎 2020-12-04 05:25

I\'ve recently come across the java @SafeVarargs annotation. Googling for what makes a variadic function in Java unsafe left me rather confused (heap poisoning?

2条回答
  •  青春惊慌失措
    2020-12-04 05:42

    For best practices, consider this.

    If you have this:

    public  void doSomething(A a, B b, T... manyTs) {
        // Your code here
    }
    

    Change it to this:

    public  void doSomething(A a, B b, T... manyTs) {
        doSomething(a, b, Arrays.asList(manyTs));
    }
    
    private  void doSomething(A a, B b, List manyTs) {
        // Your code here
    }
    

    I've found I usually only add varargs to make it more convenient for my callers. It would almost always be more convenient for my internal implementation to use a List<>. So to piggy-back on Arrays.asList() and ensure there's no way I can introduce Heap Pollution, this is what I do.

    I know this only answers your #3. newacct has given a great answer for #1 and #2 above, and I don't have enough reputation to just leave this as a comment. :P

提交回复
热议问题