Discuss / Java / 尽量模拟在无法取得Person接口定义的情况下,利用反射实现目标,本来打算用stream处理,还是没法优雅的定义。

尽量模拟在无法取得Person接口定义的情况下,利用反射实现目标,本来打算用stream处理,还是没法优雅的定义。

Topic source

张_典博

#1 Created at ... [Delete] [Delete and Lock User]

        var cls = Person.class;

        // System.out.println(Arrays.toString(cls.getDeclaredMethods()));

        for (Method mthd : cls.getDeclaredMethods()) {

            if (mthd.getReturnType() == void.class) {

                if (mthd.getName().endsWith("Name")) {

                    mthd.invoke(p, name);

                }

                if (mthd.getName().endsWith("Age")) {

                    mthd.invoke(p, age);

                }

                System.out.println(mthd);

            }

        }

        // Arrays.stream(cls.getDeclaredMethods()).

        // filter(mthd -> mthd.getReturnType() == void.class).

        // forEach((mthd -> mthd.getName().endsWith("Name") ? mthd.invoke(p, name) : mthd.invoke(p, age)));


  • 1

Reply