简体   繁体   English

Java 接口变量中的歧义

[英]Ambiguity in Java interface variable

Consider I have two interfaces having same variable names and also this variable name is same as one of the two interfaces name.考虑我有两个具有相同变量名称的接口,并且该变量名称与两个接口名称之一相同。
Eg.,例如。,

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

Say if i have a class that implements the above two interfaces and if i need to access the variable Parent1 in interface Parent1, how can i access.假设我有一个实现上述两个接口的类,如果我需要访问接口 Parent1 中的变量 Parent1,我该如何访问。
Eg.,例如。,

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
  }
}

I know the variable names does not follow standard.我知道变量名称不符合标准。 But wanted to understand how java overcomes this ambiguity.但想了解 java 如何克服这种歧义。

Edit:编辑:
People says it is working(in comments).人们说它正在工作(在评论中)。 But when I executed it says但是当我执行它时它说

/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

I would like to let you know that how java overcome this ambiguity on 'Paret1' variable while you are calling with Parent1 reference.我想让您知道,当您使用 Parent1 引用进行调用时,java 如何克服 'Paret1' 变量上的这种歧义。

Java will get exact address While you are calling Parent2.Parent1.当您调用 Parent2.Parent1 时,Java 将获得准确地址。 But due to Parent1,Parent2 interfaces implementation the property 'Parent1' is considered as an ambiguous property.但是由于 Parent1,Parent2 接口的实现,属性“Parent1”被认为是一个不明确的属性。 Since these are static variables which are saved inside method area inside JVM.由于这些是保存在 JVM 内部方法区中的静态变量。

So still if you want to access that variable value you have to give exact reference to compiler.因此,如果您想访问该变量值,则必须准确引用编译器。 for that you can use reflection.为此,您可以使用反射。 as below,如下,

 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