I am writing a small structure that instanceof should use to find out what type of callback is being passed. I already know the flaws of instanceof , but it is used in a third-party library, and I cannot change this part.
When I write lambdas and throw them away, IntelliJ warns me that casting is redundant, but actually it is necessary (it affects the result), and it works if I explicitly declare the lambda. Do you know that this is a mistake, maybe I missed something or is there a better way to do this?
Example:
public class Main { public interface Iface { String run(); } public interface IfaceA extends Iface { } public interface IfaceB extends Iface { } public static void lambdaTest(Iface iface) { System.out.print(iface.run()+": "); if (iface instanceof IfaceA) { System.out.println("IfaceA"); } else if (iface instanceof IfaceB) { System.out.println("IfaceB"); } else { System.out.println("Iface"); } } public static void main(String[] args) { lambdaTest((IfaceA)() -> "Casted to A"); lambdaTest((IfaceB)() -> "Casted to B"); lambdaTest(() -> "Not Casted"); IfaceA lambda = () -> "Declared as A"; lambdaTest(lambda); } }
And the result:
Casted to A: IfaceA Casted to B: IfaceB Not Casted: Iface Declared as A: IfaceA
But in IntelliJ I get a warning:


Javac is also tested, and I am not getting a warning:
% javac Main.java -Xlint !2525
source share