Autodetect Kotlin nullability for optional injection points (analogous to java.util.Optional)

Built-in support in MethodParameter and DependencyDescriptor supersedes our separate KotlinUtils helper.

Issue: SPR-14951
This commit is contained in:
Juergen Hoeller
2016-12-13 17:38:58 +01:00
parent 361ab6b621
commit 39d2769bd0
7 changed files with 257 additions and 150 deletions

View File

@@ -26,11 +26,18 @@ import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import kotlin.Metadata;
import kotlin.reflect.KFunction;
import kotlin.reflect.KParameter;
import kotlin.reflect.jvm.ReflectJvmMapping;
import org.springframework.util.Assert;
import org.springframework.util.KotlinUtils;
import org.springframework.util.ClassUtils;
/**
* Helper class that encapsulates the specification of a method parameter, i.e. a {@link Method}
@@ -45,12 +52,17 @@ import org.springframework.util.KotlinUtils;
* @author Rob Harrop
* @author Andy Clement
* @author Sam Brannen
* @author Sebastien Deleuze
* @since 2.0
* @see GenericCollectionTypeResolver
* @see org.springframework.core.annotation.SynthesizingMethodParameter
*/
public class MethodParameter {
private static final boolean kotlinPresent =
ClassUtils.isPresent("kotlin.Unit", MethodParameter.class.getClassLoader());
private final Method method;
private final Constructor<?> constructor;
@@ -311,11 +323,13 @@ public class MethodParameter {
/**
* Return whether this method indicates a parameter which is not required
* (either in the form of Java 8's {@link java.util.Optional} or Kotlin nullable type).
* (either in the form of Java 8's {@link java.util.Optional} or Kotlin's
* nullable type).
* @since 4.3
*/
public boolean isOptional() {
return (getParameterType() == Optional.class || KotlinUtils.isNullable(this));
return (getParameterType() == Optional.class ||
(kotlinPresent && KotlinDelegate.isNullable(this)));
}
/**
@@ -672,4 +686,40 @@ public class MethodParameter {
return parameterIndex;
}
/**
* Inner class to avoid a hard dependency on Kotlin at runtime.
*/
private static class KotlinDelegate {
/**
* Check whether the specified {@link MethodParameter} represents a nullable Kotlin type or not.
*/
public static boolean isNullable(MethodParameter param) {
if (param.getContainingClass().isAnnotationPresent(Metadata.class)) {
int parameterIndex = param.getParameterIndex();
if (parameterIndex == -1) {
KFunction<?> function = ReflectJvmMapping.getKotlinFunction(param.getMethod());
return (function != null && function.getReturnType().isMarkedNullable());
}
else {
KFunction<?> function = (param.getMethod() != null ?
ReflectJvmMapping.getKotlinFunction(param.getMethod()) :
ReflectJvmMapping.getKotlinFunction(param.getConstructor()));
if (function != null) {
List<KParameter> parameters = function.getParameters();
return parameters
.stream()
.filter(p -> KParameter.Kind.VALUE.equals(p.getKind()))
.collect(Collectors.toList())
.get(parameterIndex)
.getType()
.isMarkedNullable();
}
}
}
return false;
}
}
}

View File

@@ -1,84 +0,0 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import kotlin.Metadata;
import kotlin.reflect.KFunction;
import kotlin.reflect.KParameter;
import kotlin.reflect.jvm.ReflectJvmMapping;
import org.springframework.core.MethodParameter;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
/**
* Miscellaneous Kotlin utility methods.
*
* @author Raman Gupta
* @author Sebastien Deleuze
* @since 5.0
*/
public abstract class KotlinUtils {
private static final boolean kotlinPresent = ClassUtils.isPresent("kotlin.Unit", KotlinUtils.class.getClassLoader());
/**
* Return whether Kotlin is available on the classpath or not.
*/
public static boolean isKotlinPresent() {
return kotlinPresent;
}
/**
* Return whether the specified type is a Kotlin class or not.
*/
public static boolean isKotlinClass(Class<?> type) {
Assert.notNull(type, "Type must not be null");
return isKotlinPresent() && type.getDeclaredAnnotation(Metadata.class) != null;
}
/**
* Check whether the specified {@link MethodParameter} represents a nullable Kotlin type or not.
*/
public static boolean isNullable(MethodParameter methodParameter) {
Method method = methodParameter.getMethod();
int parameterIndex = methodParameter.getParameterIndex();
if (isKotlinClass(methodParameter.getContainingClass())) {
if (parameterIndex < 0) {
KFunction<?> function = ReflectJvmMapping.getKotlinFunction(method);
return function != null && function.getReturnType().isMarkedNullable();
}
else {
KFunction<?> function = (method != null ? ReflectJvmMapping.getKotlinFunction(method) :
ReflectJvmMapping.getKotlinFunction(methodParameter.getConstructor()));
if (function != null) {
List<KParameter> parameters = function.getParameters();
return parameters
.stream()
.filter(p -> KParameter.Kind.VALUE.equals(p.getKind()))
.collect(Collectors.toList())
.get(parameterIndex)
.getType()
.isMarkedNullable();
}
}
}
return false;
}
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core
import java.lang.reflect.Method
import org.junit.Before
import org.junit.Test
import org.junit.Assert.*
/**
* Tests for Kotlin support in [MethodParameter].
*
* @author Raman Gupta
* @author Sebastien Deleuze
* @author Juergen Hoeller
*/
class KotlinMethodParameterTests {
lateinit var nullableMethod: Method
lateinit var nonNullableMethod: Method
@Before
@Throws(NoSuchMethodException::class)
fun setup() {
nullableMethod = javaClass.getMethod("nullable", String::class.java)
nonNullableMethod = javaClass.getMethod("nonNullable", String::class.java)
}
@Test
fun `Method parameter nullability`() {
assertTrue(MethodParameter(nullableMethod, 0).isOptional())
assertFalse(MethodParameter(nonNullableMethod, 0).isOptional())
}
@Test
fun `Method return type nullability`() {
assertTrue(MethodParameter(nullableMethod, -1).isOptional())
assertFalse(MethodParameter(nonNullableMethod, -1).isOptional())
}
@Suppress("unused", "unused_parameter")
fun nullable(p1: String?): Int? = 42
@Suppress("unused", "unused_parameter")
fun nonNullable(p1: String): Int = 42
}

View File

@@ -1,62 +0,0 @@
package org.springframework.util
import org.junit.Before
import org.junit.Test
import java.lang.reflect.Method
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.springframework.core.MethodParameter
import org.springframework.util.KotlinUtils.*
/**
* Test fixture for [KotlinUtils].
*
* @author Raman Gupta
* @author Sebastien Deleuze
*/
class KotlinUtilsTests {
lateinit var nullableMethod: Method
lateinit var nonNullableMethod: Method
@Before
@Throws(NoSuchMethodException::class)
fun setup() {
nullableMethod = javaClass.getMethod("nullable", String::class.java)
nonNullableMethod = javaClass.getMethod("nonNullable", String::class.java)
}
@Test
fun `Is kotlin present`() {
// we'd have to change the build to test the opposite
assertTrue(isKotlinPresent())
}
@Test
fun `Are kotlin classes detected`() {
assertFalse(isKotlinClass(MethodParameter::class.java))
assertTrue(isKotlinClass(javaClass))
}
@Test
fun `Obtains method return type nullability`() {
assertTrue(isNullable(MethodParameter(nullableMethod, -1)))
assertFalse(isNullable(MethodParameter(nonNullableMethod, -1)))
}
@Test
fun `Obtains method parameter nullability`() {
assertTrue(isNullable(MethodParameter(nullableMethod, 0)))
assertFalse(isNullable(MethodParameter(nonNullableMethod, 0)))
}
@Suppress("unused", "unused_parameter")
fun nullable(p1: String?): Int? = 42
@Suppress("unused", "unused_parameter")
fun nonNullable(p1: String): Int = 42
}