簡體   English   中英

注釋如何防止數組參數的突變?

[英]How do annotations prevent mutations of an array parameter?

我理解注釋是不可變的,但是,Java中的數組本身並不是不可變的。 運行測試后,我注意到從注釋參數返回的數組可以變異,但它不會影響源數組:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface ArrayAnnotation {
    String[] value() default {};
}

@ArrayAnnotation({"foo"})
public class Main {
    public static void main(String[] args) {
        ArrayAnnotation test = Main.class.getAnnotation(ArrayAnnotation.class);

        String[] test0 = test.value();
        test0[0] = "bar";
        System.out.println(test0[0]);

        String[] test1 = test.value();
        System.out.println(test1[0]);
    }
}

這打印:

bar
foo

幕后發生了什么事? 在每次調用value()是否只發生了一個數組副本,還是更復雜?

在每次調用value()時是否只發生了一個數組副本,還是更復雜?

是的,數組被復制。


注釋是一種特殊的interface類型。 JLS

它們在運行時由一些Proxy類實現。 如果在Proxy.newProxyInstance()設置斷點,則可以對其進行調試。

注釋的調用被AnnotationInvocationHandler攔截,后者復制數組:

if (result.getClass().isArray() && Array.getLength(result) != 0)
     result = cloneArray(result);

你是對的,每次都會返回一份副本以確保它沒有被更改。

在Java的未來版本中,可能會優化此副本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM