How to create a library that uses AutoCloseable and also supports Java 6

I am creating a library for Java developers. I would like to create a class that implements the AutoCloseable interface if the developer uses Java 7. But I also need to provide a version of the class without the AutoCloseable interface for Android-oriented developers (which does not support AutoCloseable).

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

One solution is a preprocessor, but I am aimed at developers and cannot expect it to accept any non-standard preprocessor.

So what is best suited to support two versions of the same class depending on the version of Java?

Thanks!

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

+6
source share
2 answers
  • Make AutoCloseable Reserve

  • Make a second version of your library using backport instead of the real thing

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

For backporting:

AutoClosable can be reused as is.

For each implementation, you will need an adapter for this interface.

Trying with resources A statement might look something 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 .... } } } 

Usage will look something like this:

 new Try(){ File f = new File(); { register(closable(f)) // closabe would return an Adapter from File to AutoClosable } void execute(){ f.doSomeFunStuff() } }.do(); 
+2
source

You need two versions of your library, but if you want to have only one source code, look at AspectJ, which changes the byte code after compilation. In this case, you can get two libraries using one sozrce code, but two build targets with different AspectJ parameters.

+1
source

All Articles