假设我有一个带抽象类的库,它有一个抽象方法:
public abstract class MyAbstractClass{
public void myMethod(){
int a = doSomething("hi");
}
public abstract void doSomething(String param);
}
现在我决定在方法中添加一个参数,但是我想保留旧方法的功能以保持旧代码的可用性:
public void myMethod(){
int a = ?
}
/**
* @deprecated use doSomething(String, String) instead.
*/
@Deprecated
public int doSomething(String param){ return doSomething(param, null); }
public abstract int doSomething(String param, String secondParam);
在这种情况下,我如何实现myMethod
?
Android支持库中的PagerAdapter
类实际上有某种类似的结构,但反过来说:
public Object instantiateItem(ViewGroup container, int position) {
return instantiateItem((View) container, position);
}
/**
* @deprecated Use {@link #instantiateItem(ViewGroup, int)}
*/
public Object instantiateItem(View container, int position) {
throw new UnsupportedOperationException(
"Required method instantiateItem was not overridden");
}
是否应该阻止这种行为?如果我要使用这种结构,我怎么知道要调用什么方法?
答案 0 :(得分:2)
我想我看到了你的困境。您在库中有一个抽象类,人们正在子类化并实现它的抽象方法,并且您希望弃用此方法并添加一个新的抽象方法,而不是应该实现前进。
这就是我要做的事情:
从Feature
类开始,您的库的用户正在进行子类化
public abstract class Feature {
public abstract void doSomething(String param);
}
保持Feature
类非常实际,但是弃用该方法并在文档中宣传人们现在应该将NewFeature
子类化为Feature
而不是Feature
并实现闪亮的新抽象方法在那堂课。子类public abstract class Feature {
/**
@deprecated Extend NewFeature instead and implement doSomething(a, b)
*/
@Deprecated
public abstract void doSomething(String param);
}
public abstract class NewFeature extends Feature {
@Deprecated
@Override
public void doSomething(String param) {
doSomething(param, null);
}
public abstract void doSomething(String param, String paramTwo);
}
的现有代码仍应有效。
Feature
一旦足够的时间过去,您可以删除{{1}}课程。例如,我认为spring在第一次宣传为弃用后会倾向于删除整个版本的方法。
答案 1 :(得分:0)
根据评论,这是我要做的事情:
public void myMethod(){
int a = doSomething("hi", "theOptimalSecondArgumentValue");
}
/**
* @deprecated use doSomething(String, String) instead.
*/
@Deprecated
public abstract int doSomething(String param);
/**
* Delegates to {@link #doSomething(String)} and thus ignores the second argument
* by default. Subclasses should override this method to return a better result,
* taking the second argument into account
*/
public int doSomething(String param, String secondParam) {
return doSomething(param);
}
现有的子类仍然可以工作,但是会处于“降级”模式,其中第二个参数总是被忽略。
新的子类只需按以下方式实现:
@Override
public int doSomething(String param) {
doSomething(param, "theOptimalDefaultValue");
}
@Override
public int doSomething(String param, String secondParam) {
// compute the result using the two arguments
}