如何创建一个使用AutoCloseable并且还支持Java 6的库 [英] How to make a library which uses AutoCloseable and also support Java 6

查看:119
本文介绍了如何创建一个使用AutoCloseable并且还支持Java 6的库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Java开发人员创建一个库。我希望创建一个实现AutoCloseable接口的类,以防开发人员使用Java 7.
但是我还需要为没有AutoCloseable接口的类提供一个版本,面向Android的开发人员(不支持AutoCloseable) )。

I'm making a library for Java developers. I would like to make a class that implements the AutoCloseable interface in case the developer uses Java 7. But I also need to provide a version of the class without the AutoCloseable interface for developers targeting Android (which doesn't support AutoCloseable).

在这两种情况下,我的班级名称必须相同。

The name of my class must be the same in both cases.

一个解决方案是预处理器,但我的目标是开发人员,不能指望他们采用任何非标准的预处理器。

One solution is a preprocessor, but I'm targeting developers and can't expect them to adopt any non-standard preprocessor.

那么,支持两个版本的最佳做法是什么class取决于Java版本?

So, what is the best practice for supporting two versions of the same class depending on the Java version?

谢谢!

-
更新以澄清:< br>
两个版本的完整源代码中唯一的区别是两个单词implements AutoCloseable:

public class Transaction {...

or

公共类事务实现AutoCloseable {...

-- Update to clarify:
The ONLY difference in the full source code for the two versions would be the two words "implements AutoCloseable":
public class Transaction { ...
or
public class Transaction implements AutoCloseable {...

推荐答案


  1. 制作AutoCloseable的后端

  1. Make a backport of AutoCloseable

使用backport而不是真实的东西制作库的第二个版本

Make a 2nd Version of your library using the backport instead of the real thing

要么让用户通过实际将其作为两个工件发布来选择要使用的库,要么构建一个使用反射加载正确版本的公共外观。

Either make the user choose which library to use by actually publishing it as two artifacts, or build a common facade which loads the correct version using reflection.

对于后移:

AutoClosable可以按原样重复使用。

AutoClosable can be reused as is.

对于每个实现,您都需要一个适配器到该接口。

For each implementation, you'll need an Adapter to that interface.

try with resources Statement看起来有点像

The try with resources Statement could look somewhat like

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();

这篇关于如何创建一个使用AutoCloseable并且还支持Java 6的库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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