Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement a Java 8 interface but run on Java 6?

Tags:

java

java-8

I have an library, Fakir seeing as you ask, that I would like to keep compatible with Java 6. At the same time it would be really nice if its key abstraction, the Faker, was to be able to implement java.util.function.Supplier<T>.

I've fudged things by implementing my own copy of Supplier, so that at least lambdas can be used, but short of shipping two different jar files (ah Scala, how I miss your multiple versions for different language specs) is there any way to have my key abstraction forward compatible?

like image 390
Duncan McGregor Avatar asked May 17 '15 15:05

Duncan McGregor


2 Answers

I don't think it's possible. At some point, you need to make a leap, and your library no longer works with pre-8 java. You could do it now with pro and cons; cons being there's not many programmer familiar with java8 at this time yet.

There are some new features in Java8, like lambda, default method, static interface method, new type inference system, new utilities like Stream, that will have a big impact on how APIs are designed; they are not available to older java; and keeping compatible with older java is a handcuff to the API designers.

The pro with jumping on Java8 wagon now is that your API would be more modern, without the baggage of older java. This will pay off in the (not-very-far) future.

like image 120
ZhongYu Avatar answered Sep 25 '22 23:09

ZhongYu


As java.util.function only includes functional interfaces you can use a "backport" of it. The backport could of course not provide the default functions, only define the interfaces, but the interfaces are all you need to add compatability with Java 8.

streamsupport is a backport that adds quite a bit more than just the interfaces, but it avoids name clashing and should not require you to do two separate releases.

To use this method, if you use streamsupport, just write

import java8.util.function.*;

instead of

import java.util.function.*;

Edit: mmm-util-backport-java.util.function requires use of -Xclassbootpath as it defines java.util.function instead of the same thing with a different name, so streamsupport is the better option.

like image 32
Erik Vesteraas Avatar answered Sep 22 '22 23:09

Erik Vesteraas