# Use Functional Interfaces
# Description
Converts anonymous inner classes to equivalent lambda expressions.
# Benefits
Increases the performance, because lesser objects need to be created. Improves readability because a lot of boilerplate code will be removed.
# Tags
# Code Changes
# Remove anonymous instantiation of functional interface
Pre
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("xx");
}
};
Post
Runnable runnable = () -> {
System.out.println("xx");
};
# Rename variables if they are present in the scope outside of the inner class
Pre
int a = 5;
AFunctionalInterface foo = new AFunctionalInterface() {
@Override
public void method(int a) {
int b = a;
}
};
Post
int a = 5;
AFunctionalInterface foo = (int a1) -> {
int b = a1;
};
# Bytecode JDK 1.8
Pre
public Runnable runableWithAnonymousClass() {
Runnable r = new Runnable() {
public void run() {
System.out.println("Anonymous class");
}
};
return r;
}
0 new #2 <at/splendit/AnonymousClassesToLambdaExpressions$1>
3 dup
4 aload_0
5 invokespecial #3 <at/splendit/AnonymousClassesToLambdaExpressions$1.<init>>
8 astore_1
9 aload_1
10 areturn
Post
public Runnable runableWithLambda() {
Runnable r = () -> {
System.out.println("Lambda");
};
return r;
}
0 invokedynamic #4 <run, BootstrapMethods #0>
5 astore_1
6 aload_1
7 areturn
0 getstatic #5 <java/lang/System.out>
3 ldc #6 <Lambda>
5 invokevirtual #7 <java/io/PrintStream.println>
8 return
# Limitations
Variables that are used inside the anonymous class must be effectively final.
🛠️ Auto-refactor Available
You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:
Need help? Check out our installation guide.