我正在为Java开发人员创建一个库。我想创建一个实现AutoCloseable接口的类,以防开发人员使用Java7。但我还需要为面向安卓(不支持AutoCloseable)的开发人员提供一个没有AutoCloseable接口的类版本。
在这两种情况下,我的类的名称必须相同。
一种解决方案是预处理器,但我的目标是开发人员,不能期望他们采用任何非标准的预处理器。
那么,根据Java版本支持同一类的两个版本的最佳实践是什么?
谢谢!
--更新以澄清:
两个版本的完整源代码中唯一的区别是"implements“这两个字:
public class Transaction { ...或
public class Transaction implements AutoCloseable {...发布于 2012-11-23 17:27:29
对于回迁:
AutoClosable可以按原样重用。
对于每个实现,您都需要该接口的Adapter。
try with resources语句可能看起来有点像
abstract public class Try {
private List<AutoClosable> closables = new ArrayList<>();
public void register(AutoClosable closable){
closables.add(closable);
}
abstract void execute();
public void do(){
try{
execute()
} finally {
for (AutoClosable c : closables)
c.close() // there are tons of exceptionhandling missing here, and the order might need to get reversed ....
}
}
}用法看起来有点像:
new Try(){
File f = new File();
{
register(closable(f)) // closabe would return an Adapter from File to AutoClosable
}
void execute(){
f.doSomeFunStuff()
}
}.do();发布于 2012-11-23 17:52:51
您需要两个版本的库,但是如果您只想拥有一个源代码,请看一下AspectJ,它在编译后修改字节码。通过这种方式,您可以使用一个源代码获得两个库,但使用不同的AspectJ选项获得两个构建目标。
https://stackoverflow.com/questions/13526007
复制相似问题