Java怪事之匿名类无法通过反射获取到的类中获取到一些如函数、出

2022-09-30  本文已影响0人  东南枝下
@FunctionalInterface
public interface Action<T, V> {

    /**
     * 执行操作
     *
     * @param param 入参
     * @return 返回参数
     */
    V execute(T param);
}

public class FlowNode {

    public FlowNode(String name, Action<?, ?> action) {
        Class<?> clz = action.getClass();
        this.name = name;
        this.action = action;
        this.next = new ArrayList<>();
    }

......

FlowNode two = new FlowNode("two", (Action<Boy, Girl>) boy -> {
            boy.setAge(boy.getAge() + 1);
            System.out.println("第 3 个节点------参数:" + boy);
            Girl girl = new Girl();
            BeanUtils.copyProperties(boy, girl);
            return girl;
        });

方式二:匿名对象,其实和lambda是一样的

FlowNode two = new FlowNode("two", new Action<Boy, Girl>() {
            @Override
            public Girl execute(Boy boy) {
                boy.setAge(boy.getAge() + 1);
                System.out.println("第 3 个节点------参数:" + boy);
                Girl girl = new Girl();
                BeanUtils.copyProperties(boy, girl);
                return girl;
            }
        });

如图所示,是获取不到具体的类型的,就没法通过反射做一些事情


image.png
上一篇 下一篇

猜你喜欢

热点阅读