[英]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.