簡體   English   中英

Java 接口變量中的歧義

[英]Ambiguity in Java interface variable

考慮我有兩個具有相同變量名稱的接口,並且該變量名稱與兩個接口名稱之一相同。
例如。,

interface Parent1{  
  public static final String Parent1= "VALUE1";  // Variable Parent1 is same as interface name 
}  
interface Parent2{  
  public static final String Parent1= "VALUE2";  
}

假設我有一個實現上述兩個接口的類,如果我需要訪問接口 Parent1 中的變量 Parent1,我該如何訪問。
例如。,

class Child implements Parent1, Parent2{
  void myCode(){
    System.out.println(Parent1.Parent1); // Does not compile. Because Parent1(before dot) is considered as variable
    System.out.println(Parent2.Parent1); // Does compile
  }
}

我知道變量名稱不符合標准。 但想了解 java 如何克服這種歧義。

編輯:
人們說它正在工作(在評論中)。 但是當我執行它時它說

/Child.java:9: error: reference to Parent1 is ambiguous
        System.out.println(Parent1.Parent1); // Does not compile. Because Parent1(before dot) is considered as variable
                           ^
  both variable Parent1 in Parent1 and variable Parent1 in Parent2 match
/Child.java:9: error: cannot find symbol
        System.out.println(Parent1.Parent1); // Does not compile. Because Parent1(before dot) is considered as variable
                                  ^
  symbol:   variable Parent1
  location: variable Parent1 of type String
2 errors

我想讓您知道,當您使用 Parent1 引用進行調用時,java 如何克服 'Paret1' 變量上的這種歧義。

當您調用 Parent2.Parent1 時,Java 將獲得准確地址。 但是由於 Parent1,Parent2 接口的實現,屬性“Parent1”被認為是一個不明確的屬性。 由於這些是保存在 JVM 內部方法區中的靜態變量。

因此,如果您想訪問該變量值,則必須准確引用編譯器。 為此,您可以使用反射。 如下,

 try {
        Class parent = Class.forName("yourpackage.Parent1");
        Field field = parent.getDeclaredField("Parent1");
        field.setAccessible(true);
        Object value = field.get(parent);
        System.out.println(value); // this will print out the 'Parent1' value

    } catch (Exception e) {
        e.printStackTrace();
    }

暫無
暫無

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

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