Java匿名内部类 labmda表达式 传统风格 对比

传统风格

class MyInvocationHandler implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] handlerArgs) throws Throwable {
        if ("eat".equals(method.getName())) {
            System.out.println("我可以吃香喝辣!");
            return null;
        }
        if ("write".equals(method.getName())) {
            System.out.println("我的作文题目是《我的区长父亲》。");
            method.invoke(ordinaryStudents, handlerArgs);
            System.out.println("我的作文拿了区作文竞赛一等奖!so easy!");
            return null;
        }
        return null;
    }
}

// 使用MyInvocationHandler
InvocationHandler handler = new MyInvocationHandler();

匿名内部类

InvocationHandler handler = new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] handlerArgs) throws Throwable {
        if ("eat".equals(method.getName())) {
            System.out.println("我可以吃香喝辣!");
            return null;
        }
        if ("write".equals(method.getName())) {
            System.out.println("我的作文题目是《我的区长父亲》。");
            method.invoke(ordinaryStudents, handlerArgs);
            System.out.println("我的作文拿了区作文竞赛一等奖!so easy!");
            return null;
        }
        return null;
    }
};

labmda表达式

 


InvocationHandler handler = (proxy, method, handlerArgs) -> {
// 从定义eat方法。
if ("eat".equals(method.getName())) {
System.out.println("我可以吃香喝辣!");
return null;
}
// 从定义write方法。
if ("write".equals(method.getName())) {
System.out.println("我的作文题目是《我的区长父亲》。");
// 调用普通学生类的write方法,流程还是要走的,还是要交一篇作文上去,不能太明目张胆。
method.invoke(ordinaryStudents, handlerArgs);
System.out.println("我的作文拿了区作文竞赛一等奖!so easy!");
return null;
}
return null;
};

posted @ 2024-03-01 11:00  予真  阅读(20)  评论(0)    收藏  举报