问题
Does anyone know of any tool to convert Java 8 code (at the source level) that uses lambdas and method references into Java 7 code that uses anonymous inner classes? I know about Retrolambda, but that works at the bytecode level, not the source level.
For now, I have a version working that works as an IntelliJ plugin. I extended the current IntelliJ code to convert all lambdas in a package at one go, instead of selecting each lambda individually and converting to anonymous inner class. The problem with this approach though is that it cannot work as a standalone tool, say a maven plugin as it needs an IntelliJ context to work.
Edit: Note that the focus is on converting lamda/method references to anonymous inner classes. I am not concerned about API changes in Java 8 which would be caught by a Java 7 compiler and reported as compilation errors.
回答1:
In IntelliJ Idea open 'Project Structure' and then set Project language level to 7.0. Analyze your code again if that is needed. That will help in most of the cases but prefer to do it class by class (file by file) basis.
回答2:
You can try this. It's one person's proof-of-concept to do something close to what you are asking:
It can convert a variable declaration for a functional interface with a lambda initializer into a anonymous inner class.
e.g.:
Callable<String> callable = () -> "abc" ;
// Converted to:
Callable<String> callable = new Callable<String>() {
public String call() throws java.lang.Exception {
return "abc";
}
};
I don't know if it can convert anonymous lambdas (i.e. those not declared as a variable) or Method References (e.g. Person::compareByAge
), or closures (local variable capture), but those might be features you can extend his code to do if you need them.
The author notes that "It's a long way from being feature complete, but it's usable..."
来源:https://stackoverflow.com/questions/24943726/tool-to-delambdafy-java-code-from-java-8-to-java-7-syntax