首页 新闻 会员 周边

java8通过反射获取接口的默认方法

0
[待解决问题]

如何通过反射获取接口的默认方法使用

xnhel的主页 xnhel | 初学一级 | 园豆:4
提问于:2022-12-28 17:02
< >
分享
所有回答(1)
0

假设我们有以下接口:

public interface MyInterface {
    default void defaultMethod() {
        System.out.println("Default method");
    }
    void abstractMethod();
}

可以通过反射获取默认方法并调用它:

import java.lang.reflect.Method;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws Exception {
        Class<MyInterface> clazz = MyInterface.class;
        Method[] methods = clazz.getDeclaredMethods();
        Arrays.stream(methods)
                .filter(Method::isDefault)
                .forEach(method -> {
                    try {
                        method.invoke(new MyInterface() {}, null);
                    } catch (Exception e) {
                        System.err.println("Error invoking default method: " + e);
                    }
                });
    }
}

心若向阳花自开 | 园豆:290 (菜鸟二级) | 2023-03-08 14:54

非常感谢,不过这个问题我已经解决了

支持(0) 反对(0) xnhel | 园豆:4 (初学一级) | 2023-03-08 14:57
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册