对于类A、B,A是B的基类,A有一个私有成员name

A.java

public class A {
    private String name = "A";

    public void print() {
        System.out.println(name);
    }
}

B.java

public class B extends A {
}

对于A对象a,要想改变a的name,可以这样操作:

        try {
            Field nameFieldInA = a.getClass().getDeclaredField("name");
            nameFieldInA.setAccessible(true);
            nameFieldInA.set(a, "一");
            a.print();
        } catch (NoSuchFieldException | IllegalAccessException ex) {
            ex.printStackTrace();
        }

要访问a的name,可执行nameFieldInA.get(a)

对于B对象b,要改变b的name,可以这样:

import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) {
        try {
            B b = new B();
            b.print();
            Field field = b.getClass().getSuperclass().getDeclaredField("name");
            field.setAccessible(true);
            field.set(b, "B");
            b.print();
        } catch (NoSuchFieldException | IllegalAccessException ex) {
            ex.printStackTrace();
        }
    }
}

 

相关文章:

  • 2021-07-11
  • 2021-09-05
  • 2022-02-13
  • 2022-12-23
  • 2021-12-10
  • 2021-09-29
  • 2021-06-22
  • 2022-12-23
猜你喜欢
  • 2021-05-26
  • 2021-10-14
  • 2021-12-19
  • 2021-08-29
  • 2022-12-23
  • 2022-12-23
  • 2021-06-11
相关资源
相似解决方案