简体   繁体   English

java中如何在Main方法中访问同名变量不同类变量

[英]How to Access same name Variable Different Class Variable in Main Method in java

Accessing Same Name Data Members In Main Method Using obj Object not creating object in Class A and Class B.使用 obj 对象访问 Main 方法中的同名数据成员,而不是在 A 类和 B 类中创建对象。

class A {
  int i = 10;
}
class B extends A {
 int i = 20;
}
class C extends B {
  int i = 30;
}
public class Main {
  public static void main (String[] args)   {
    C obj = new C ();
    System.out.println (obj.i);
    //How to access Class A variable
    //How to access Class B Variable
  }
}

Print Class A Variable Print Class B Variable Without Creating Object of Class A and Class B.打印 A 类变量打印 B 类变量而不创建 A 类和 B 类对象。

System.out.println (((A) obj).i); and System.out.println (((B) obj).i);System.out.println (((B) obj).i); respectively.分别。 If they were protected fields, they would be inherited.如果它们是protected字段,它们将被继承。 As is, they are hidden ( shadowed ) package-private fields.原样,它们是隐藏(阴影)包私有字段。

Since you've now mentioned that you cannot use a simple cast, the next best option (I can think of) is reflection .由于您现在已经提到不能使用简单的强制转换,因此下一个最佳选择(我能想到的)是反射 You can iterate the Field (s), find the field named i , make it accessible and then print it (and the class name).您可以迭代Field (s),找到名为i的字段,使其可访问,然后打印它(和类名)。 For example,例如,

try {
    Class<?>[] classes = { A.class, B.class, C.class };
    for (Class<?> cls : classes) {
        for (Field f : cls.getDeclaredFields()) {
            if (f.getName().equals("i")) {
                f.setAccessible(true);
                System.out.printf("%s %s%n", cls.getSimpleName(), f.get(obj));
            }
        }
    }
} catch (IllegalArgumentException | IllegalAccessException | SecurityException e) {
    e.printStackTrace();
}

Outputs输出

A 10
B 20
C 30

Use the Reflection.使用反射。 You can get the super class and get the i value.您可以获得超类并获得 i 值。 This approach don't use the typeCasting, create object and statie member.这种方法不使用 typeCasting、create object 和 statie 成员。 I think it will help you.我想它会帮助你。

class A {
    int i = 10;
}
class B extends A {
    int i = 20;
}
class C extends B {
    int i = 30;
}
public class Main {
    public static void main (String[] args)   {
        try {
            C obj = new C();
            System.out.println(obj.i);
            // get the Class B
            Class b = obj.getClass().getSuperclass();
            System.out.println(b.getDeclaredField("i").getInt(obj));
            // get the Class A
            Class a = b.getSuperclass();
            System.out.println(a.getDeclaredField("i").getInt(obj));
        } catch (Exception e) {
            // ignore
        }

        // Output
        // 30
        // 20
        // 10
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java - 如何通过 main 方法在不同的类中存储变量? - Java - How to store a variable via main method in a different class? 如何在同一 class 中的 java 中访问存储在另一种方法中的变量 - How to access a variable stored in another method in java in the same class 如何访问同名的外部类变量? - How to access outer class variable of same name? Java:如何通过保存在变量中的名称访问类? - Java: how to access a class by a name saved in a variable? 如何在不同的类Java中访问私有变量 - How to access private variable in different class Java java中其他class的方法如何访问变量 - How to access the variable in the method of other class in java 如何从动作侦听器/类构造函数访问变量以在java的main方法中使用 - How to access variable from action listener/class constructor to use in main method in java 来自相同类但方法不同的访问变量-Android Eclipse-App - Access Variable from the same Class but different method - Android Eclipse - App 命名约定 Java 用于不同的 class 但变量名称相同 - Naming Convention Java for different class but same variable name 同名的类方法和变量,在 C++ 中编译错误而不是在 Java 中? - Class method and variable with same name, compile error in C++ not in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM