force base class to use its own method and not overrided method

青春壹個敷衍的年華 提交于 2019-12-31 01:00:34

问题


here is my scenario:

class SomeBaseClass
{
     public void foo(String str)
     {
     .......
     }
     public void foo(String strs[])
     {
     .......
     }
}

class MyClass extends SomeBaseClass
{
     public void foo(String str)
     {
           super.foo(str);
     }
     public void foo(String strs[])
     {
           throw new RuntimeException("only one input please!");
     }
}

The logic is pretty simple. "SomeBaseClass" is 3rd party tool that i cannot modify. I want to limit its functionality and don't want to allow foo(String strs[]).

the problem is that inside SomeBaseClass foo(Sting str) internally calls foo(String strs[]). Hence when i call foo(String str) of MyClass, I get a runtime exception. How can I tell the SomeBaseClassclass to use SomeBaseClass::foo(String strs[]) and all other classes to use MyClass ::foo(String strs[])


回答1:


Perhaps over engg but inside MyClass.foo(String strs[]) you can check if the caller is SomeBaseClass.foo(String str), if yes, let the call go thru to super.foo(String) else throw RuntimeException.

To find the caller check StackTrace.




回答2:


Consider writing a wrapper

class MyClass extends SomeBaseClass
{
    private SomeBaseClass impl = new SomeBaseClass ();

    public void foo(String str)
    {
        impl.foo(str);
    }

    public void foo(String strs[])
    {
        throw new RuntimeException("only one input please!");
    }
}


来源:https://stackoverflow.com/questions/7520359/force-base-class-to-use-its-own-method-and-not-overrided-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!