覆盖实例化的Java对象中的方法 [英] Overriding a method in an instantiated Java object

查看:127
本文介绍了覆盖实例化的Java对象中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想覆盖一个由我无法控制的工厂交给我的对象中的方法。

I would like to override a method in an object that's handed to me by a factory that I have little control over.

我的具体问题是我要覆盖套接字对象<的 getInputStream getOutputStream / strong>执行 电汇记录

My specific problem is that I want to override the getInputStream and getOutputStream of a Socket object to perform wire logging.

一般问题如下:

public class Foo {
    public Bar doBar() {
        // Some activity
    }
}

我想要实例化 Foo 并将 doBar 替换为我自己的工作,如下所示:

Where I'd like to take an instantiated Foo and replace the doBar with my own that would work as follows:

Bar doBar() {
    // My own activity
    return original.doBar();
}

对于Socket,我将返回 InputStream OutputStream ,它们通过记录来拦截数据。

For the Socket I'm going to return an InputStream and OutputStream that are wrapped by logging to intercept the data.

推荐答案

由于Java使用类基于OO,这是不可能的。您可以使用装饰器模式,即为返回包装的对象编写包装器溪流。

Since Java uses class-based OO, this is impossible. What you can do is use the decorator pattern, i.e. write a wrapper for the object that returns the wrapped streams.

这篇关于覆盖实例化的Java对象中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆