Issue
I have problem on java 11 predicate lambda expression generic type , when I write predicate as lambda expression is not returning exactly generic parameter ,and ClassCastException
occurs , code seen below
Explaination
When we write lambda expression , Generic Parameter method getGenericInterfaces()[0] -> ClassCastException
occurs this line because there no generic parameter seen when I debugged code , seen as just Condition not Condition<<Integer>>
, anyway when we define predicate as seen below (working case) , its working
Working Case
Condition<Integer> oddValueCondition = new Condition<Integer>() {
@Override
public boolean test(Integer integer) {
return integer % 2 == 0;
}
};
Not Working Case
Condition<Integer> oddValueCondition = integer -> integer % 2 == 0;
interface definition
@FunctionalInterface
public interface Condition<T> extends Predicate<T> {
default Class<T> getParameterType() {
ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericInterfaces()[0];
Type[] typeArguments = parameterizedType.getActualTypeArguments();
Class<T> type = (Class<T>) typeArguments[0];
return type;
}
}
Test
oddValueCondition.getParameterType();
So what do you think problem is , when write lambda expression ?
And also I created issue on the github OpenJDK
if they says TypeReference
Hack is not work on anonymous class and lambda expression , I will accept answer
Solution
Lambda expressions and anonymous inner classes don't compile to the same byte-code
.
The TypeReference
hack doesn't work with lambda as the type information is not available through this API. And by the way, this has been like this since Java 1.8.
Answered By - Sleiman Jneidi
Answer Checked By - Mildred Charles (JavaFixing Admin)