Tyl*_*abo 31 java oop methods overriding
我想覆盖一个由我无法控制的工厂交给我的对象中的方法.
我的具体问题是,我想覆盖的getInputStream和getOutputStream方法一的Socket对象进行线记录.
一般问题如下:
public class Foo {
public Bar doBar() {
// Some activity
}
}
Run Code Online (Sandbox Code Playgroud)
在哪里我想要实例化Foo并替换doBar我自己的工作方式如下:
Bar doBar() {
// My own activity
return original.doBar();
}
Run Code Online (Sandbox Code Playgroud)
对于Socket,我将返回一个InputStream和OutputStream,它们通过记录来拦截数据.
小智 13
我认为有一种方法可以达到你想要的效果.我看到它通常用于带有按钮的摆动,以允许程序员在按下按钮时执行某些操作.
假设你有你的Foo课程:
public class Foo {
public Bar doBar() {
// Some activity
}
}
Run Code Online (Sandbox Code Playgroud)
然后你有一个跑步者类或类似的东西.您可以在实例化时覆盖doBar()方法,它只会影响该特定对象.
该类可能如下所示:
public class FooInstance{
Foo F1 = new Foo(){
public Bar doBar(){
//new activity
}
}
Foo F2 = new Foo();
F1.doBar(); //does the new activity
F2.doBar(); //does the original activity found in the class
}
Run Code Online (Sandbox Code Playgroud)
我不完全确定会为你做什么,但也许它会让你朝着正确的方向前进.如果没有别的东西可以覆盖课外的方法,也许这会对你有所帮助.
您无法替换现有对象中的方法 - 您无法更改现有对象的类型.
您可以创建委托给现有实例的另一个类的新实例,但这也有局限性.
在你的真实世界的情况下你是不是可以简单地单独调用来包装套接字返回的流?你能提供更多细节吗?