Java

Java中super关键字如何配合反射使用

小樊
92
2024-08-02 21:38:15
栏目: 编程语言

在Java中,可以使用反射来调用父类的方法或字段,同时也可以使用super关键字来访问父类的方法或字段。下面是一个示例,演示了如何结合super关键字和反射来调用父类的方法:

import java.lang.reflect.Method;

class Parent {
    public void sayHello() {
        System.out.println("Hello from Parent");
    }
}

class Child extends Parent {
    @Override
    public void sayHello() {
        try {
            Method method = Parent.class.getDeclaredMethod("sayHello");
            method.invoke(super, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.sayHello();
    }
}

在上面的示例中,Child类继承自Parent类,并且重写了Parent类的sayHello方法。在Child类的sayHello方法中,使用反射获取Parent类的sayHello方法,并通过method.invoke(super, null)来调用父类的sayHello方法。最终输出结果为:

Hello from Parent

0
看了该问题的人还看了