Skip to content

Commit

Permalink
Support correct type analysis with generic return type of Optional
Browse files Browse the repository at this point in the history
  • Loading branch information
lucamolteni committed Sep 1, 2020
1 parent 4e7ceea commit 98dae05
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/main/java/org/mvel2/compiler/PropertyVerifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package org.mvel2.compiler;

import java.lang.reflect.Field;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
Expand Down Expand Up @@ -669,7 +670,14 @@ else if (typeArgs.containsKey(returnTypeArg)) {
}

private static Class type2Class(Type type) {
return type instanceof Class ? (Class) type : (Class) ((ParameterizedType) type).getRawType();
if (type instanceof Class) {
return (Class) type;
} else if(type instanceof TypeVariable) { // such as T in Optional<T>
GenericDeclaration genericDeclaration = ((TypeVariable) type).getGenericDeclaration();
return ((Method)genericDeclaration).getReturnType();
} else {
return (Class) ((ParameterizedType) type).getRawType();
}
}

private Class getWithProperty(Class ctx) {
Expand Down
11 changes: 11 additions & 0 deletions src/test/java/org/mvel2/tests/core/TypesAndInferenceTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import static org.mvel2.MVEL.*;
Expand Down Expand Up @@ -1595,4 +1596,14 @@ public void testGenerics1() {
assertTrue(result);
}

public void testOptionalOfGenerics() {
String str = "Optional.of(\"mystring\").orElse(\"anotherstring\")";

ParserConfiguration pconf = new ParserConfiguration();
ParserContext pctx = new ParserContext(pconf);
pctx.setStrongTyping(true);
pctx.addImport(Optional.class);
Class resultType = analyze(str, pctx);
assertEquals(java.util.Optional.class, resultType);
}
}

0 comments on commit 98dae05

Please sign in to comment.