Skip to content

Commit

Permalink
Merge pull request mvel#244 from lucamolteni/master
Browse files Browse the repository at this point in the history
Support correct type analysis with generic return type of Optional
  • Loading branch information
mariofusco authored Sep 2, 2020
2 parents 4e7ceea + b55a0e1 commit aa044be
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
18 changes: 16 additions & 2 deletions 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 @@ -668,8 +669,21 @@ else if (typeArgs.containsKey(returnTypeArg)) {
return getReturnType(ctx, m);
}

private static Class type2Class(Type type) {
return type instanceof Class ? (Class) type : (Class) ((ParameterizedType) type).getRawType();
private static Class<?> type2Class(Type type) {
if (type == null) {
return null;
}
if (type instanceof Class<?>) {
return (Class) type;
}
if (type instanceof ParameterizedType) {
return type2Class(((ParameterizedType) type).getRawType());
}
if (type instanceof TypeVariable) { // this is T in Optional<T>
GenericDeclaration genericDeclaration = ((TypeVariable) type).getGenericDeclaration();
return genericDeclaration instanceof Method ? ((Method) genericDeclaration).getReturnType() : Object.class;
}
throw new UnsupportedOperationException("Unknown type " + type);
}

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 aa044be

Please sign in to comment.