Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support generic type for request type #642

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions services-api/src/main/java/io/scalecube/services/ClassUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package io.scalecube.services;

import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Objects;

/**
* Miscellaneous {@code java.lang.Class} utility methods.
* */
public class ClassUtils {

private ClassUtils() {
// Do not instantiate
}

/**
* Map with primitive wrapper type as key and corresponding primitive type as value, for example:
* Integer.class -> int.class.
*/
private static final Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new IdentityHashMap<>(8);

/**
* Map with primitive type as key and corresponding wrapper type as value, for example: int.class
* -> Integer.class.
*/
private static final Map<Class<?>, Class<?>> primitiveTypeToWrapperMap = new IdentityHashMap<>(8);

static {
primitiveWrapperTypeMap.put(Boolean.class, boolean.class);
primitiveWrapperTypeMap.put(Byte.class, byte.class);
primitiveWrapperTypeMap.put(Character.class, char.class);
primitiveWrapperTypeMap.put(Double.class, double.class);
primitiveWrapperTypeMap.put(Float.class, float.class);
primitiveWrapperTypeMap.put(Integer.class, int.class);
primitiveWrapperTypeMap.put(Long.class, long.class);
primitiveWrapperTypeMap.put(Short.class, short.class);

// Map entry iteration is less expensive to initialize than forEach with lambdas
for (Map.Entry<Class<?>, Class<?>> entry : primitiveWrapperTypeMap.entrySet()) {
primitiveTypeToWrapperMap.put(entry.getValue(), entry.getKey());
}
}

/**
* Check if the right-hand side type may be assigned to the left-hand side type, assuming setting
* by reflection. Considers primitive wrapper classes as assignable to the corresponding primitive
* types.
*
* @param lhsType the target type
* @param rhsType the value type that should be assigned to the target type
* @return if the target type is assignable from the value type // * @see TypeUtils#isAssignable
*/
public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) {
Objects.requireNonNull(lhsType, "Left-hand side type must not be null");
Objects.requireNonNull(rhsType, "Right-hand side type must not be null");
if (lhsType.isAssignableFrom(rhsType)) {
return true;
}
if (lhsType.isPrimitive()) {
return lhsType == primitiveWrapperTypeMap.get(rhsType);
} else {
Class<?> resolvedWrapper = primitiveTypeToWrapperMap.get(rhsType);
return resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper);
}
}
}
67 changes: 21 additions & 46 deletions services-api/src/main/java/io/scalecube/services/Reflect.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,22 @@ public static Type parameterizedReturnType(Method method) {
return method.getAnnotation(ResponseType.class).value();
}

Type type = method.getGenericReturnType();
if (type instanceof ParameterizedType) {
Type actualReturnType = ((ParameterizedType) type).getActualTypeArguments()[0];
Class<?> methodReturnType = method.getReturnType();

if (Publisher.class.isAssignableFrom(methodReturnType)) {
Type actualReturnType =
((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0];
if (ServiceMessage.class.equals(actualReturnType)) {
return Object.class;
}

return actualReturnType;
} else {
}

if (ServiceMessage.class.equals(methodReturnType)) {
return Object.class;
}

return methodReturnType;
}

/**
Expand Down Expand Up @@ -89,26 +93,29 @@ public static boolean isReturnTypeServiceMessage(Method method) {
* @param method in inspection.
* @return type of parameter [0] or void
*/
public static Class<?> requestType(Method method) {
public static Type requestType(Method method) {
if (method.getParameterTypes().length > 0) {
if (method.isAnnotationPresent(RequestType.class)) {
return method.getAnnotation(RequestType.class).value();
} else {
if (method.getParameters()[0].isAnnotationPresent(Principal.class)) {
return Void.TYPE;
}

if (method.getGenericParameterTypes()[0] instanceof ParameterizedType) {
try {
return Class.forName(parameterizedRequestType(method).getTypeName());
} catch (ClassNotFoundException e) {
Class<?> parameterType = method.getParameterTypes()[0];
Type genericType = method.getGenericParameterTypes()[0];
if (Publisher.class.isAssignableFrom(parameterType)) {
Type actualRequestType = ((ParameterizedType) genericType).getActualTypeArguments()[0];
if (ServiceMessage.class.equals(actualRequestType)) {
return Object.class;
}
} else if (ServiceMessage.class.equals(method.getParameterTypes()[0])) {
return actualRequestType;
}

if (ServiceMessage.class.equals(parameterType)) {
return Object.class;
} else {
return method.getParameterTypes()[0];
}

return genericType;
}
} else {
return Void.TYPE;
Expand All @@ -127,22 +134,6 @@ public static boolean isRequestTypeServiceMessage(Method method) {
return parameterTypes.length > 0 && ServiceMessage.class.equals(parameterTypes[0]);
}

/**
* Util function that returns the parameterizedType of a given object.
*
* @param object to inspect
* @return the parameterized Type of a given object or Object class if unknown.
*/
public static Type parameterizedType(Object object) {
if (object != null) {
Type type = object.getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
return ((ParameterizedType) type).getActualTypeArguments()[0];
}
}
return Object.class;
}

/**
* Parse <code>serviceInterface</code> class and puts available methods annotated by {@link
* ServiceMethod} annotation to {@link Method} -> {@link MethodInfo} mapping.
Expand Down Expand Up @@ -170,22 +161,6 @@ public static Map<Method, MethodInfo> methodsInfo(Class<?> serviceInterface) {
isAuth(method1)))));
}

/**
* Util function that returns the parameterized of the request Type of a given object.
*
* @return the parameterized Type of a given object or Object class if unknown.
*/
public static Type parameterizedRequestType(Method method) {
if (method != null && method.getGenericParameterTypes().length > 0) {
Type type = method.getGenericParameterTypes()[0];
if (type instanceof ParameterizedType) {
return ((ParameterizedType) type).getActualTypeArguments()[0];
}
}

return Object.class;
}

/**
* Util function to extract service name from service api.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ public <T> T api(Class<T> serviceInterface) {
final Type returnType = methodInfo.parameterizedReturnType();
final boolean isServiceMessage = methodInfo.isReturnTypeServiceMessage();

Object request = methodInfo.requestType() == Void.TYPE ? null : params[0];
Object request = methodInfo.isRequestTypeVoid() ? null : params[0];

switch (methodInfo.communicationMode()) {
case FIRE_AND_FORGET:
Expand Down
200 changes: 200 additions & 0 deletions services-api/src/main/java/io/scalecube/services/TypeUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
package io.scalecube.services;

import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.Objects;

/** Utility to work with Java 5 generic type parameters. */
public class TypeUtils {

private TypeUtils() {
// Do not instantiate
}

/**
* Check if the right-hand side type may be assigned to the left-hand side type following the Java
* generics rules.
*
* @param lhsType the target type
* @param rhsType the value type that should be assigned to the target type
* @return true if rhs is assignable to lhs
*/
public static boolean isAssignable(Type lhsType, Type rhsType) {
Objects.requireNonNull(lhsType, "Left-hand side type must not be null");
Objects.requireNonNull(rhsType, "Right-hand side type must not be null");

// all types are assignable to themselves and to class Object
if (lhsType.equals(rhsType) || Object.class == lhsType) {
return true;
}

if (lhsType instanceof Class) {
Class<?> lhsClass = (Class<?>) lhsType;

// just comparing two classes
if (rhsType instanceof Class) {
return ClassUtils.isAssignable(lhsClass, (Class<?>) rhsType);
}

if (rhsType instanceof ParameterizedType) {
Type rhsRaw = ((ParameterizedType) rhsType).getRawType();

// a parameterized type is always assignable to its raw class type
if (rhsRaw instanceof Class) {
return ClassUtils.isAssignable(lhsClass, (Class<?>) rhsRaw);
}
} else if (lhsClass.isArray() && rhsType instanceof GenericArrayType) {
Type rhsComponent = ((GenericArrayType) rhsType).getGenericComponentType();

return isAssignable(lhsClass.getComponentType(), rhsComponent);
}
}

// parameterized types are only assignable to other parameterized types and class types
if (lhsType instanceof ParameterizedType) {
if (rhsType instanceof Class) {
Type lhsRaw = ((ParameterizedType) lhsType).getRawType();

if (lhsRaw instanceof Class) {
return ClassUtils.isAssignable((Class<?>) lhsRaw, (Class<?>) rhsType);
}
} else if (rhsType instanceof ParameterizedType) {
return isAssignable((ParameterizedType) lhsType, (ParameterizedType) rhsType);
}
}

if (lhsType instanceof GenericArrayType) {
Type lhsComponent = ((GenericArrayType) lhsType).getGenericComponentType();

if (rhsType instanceof Class) {
Class<?> rhsClass = (Class<?>) rhsType;

if (rhsClass.isArray()) {
return isAssignable(lhsComponent, rhsClass.getComponentType());
}
} else if (rhsType instanceof GenericArrayType) {
Type rhsComponent = ((GenericArrayType) rhsType).getGenericComponentType();

return isAssignable(lhsComponent, rhsComponent);
}
}

if (lhsType instanceof WildcardType) {
return isAssignable((WildcardType) lhsType, rhsType);
}

return false;
}

private static boolean isAssignable(ParameterizedType lhsType, ParameterizedType rhsType) {
if (lhsType.equals(rhsType)) {
return true;
}

Type[] lhsTypeArguments = lhsType.getActualTypeArguments();
Type[] rhsTypeArguments = rhsType.getActualTypeArguments();

if (lhsTypeArguments.length != rhsTypeArguments.length) {
return false;
}

for (int size = lhsTypeArguments.length, i = 0; i < size; ++i) {
Type lhsArg = lhsTypeArguments[i];
Type rhsArg = rhsTypeArguments[i];

if (!lhsArg.equals(rhsArg)
&& !(lhsArg instanceof WildcardType && isAssignable((WildcardType) lhsArg, rhsArg))) {
return false;
}
}

return true;
}

private static boolean isAssignable(WildcardType lhsType, Type rhsType) {
Type[] lhsUpperBounds = lhsType.getUpperBounds();

// supply the implicit upper bound if none are specified
if (lhsUpperBounds.length == 0) {
lhsUpperBounds = new Type[] {Object.class};
}

Type[] lhsLowerBounds = lhsType.getLowerBounds();

// supply the implicit lower bound if none are specified
if (lhsLowerBounds.length == 0) {
lhsLowerBounds = new Type[] {null};
}

if (rhsType instanceof WildcardType) {
// both the upper and lower bounds of the right-hand side must be completely enclosed in the
// upper and lower bounds of the left-hand side.
WildcardType rhsWcType = (WildcardType) rhsType;
Type[] rhsUpperBounds = rhsWcType.getUpperBounds();

if (rhsUpperBounds.length == 0) {
rhsUpperBounds = new Type[] {Object.class};
}

Type[] rhsLowerBounds = rhsWcType.getLowerBounds();

if (rhsLowerBounds.length == 0) {
rhsLowerBounds = new Type[] {null};
}

for (Type lhsBound : lhsUpperBounds) {
for (Type rhsBound : rhsUpperBounds) {
if (!isAssignableBound(lhsBound, rhsBound)) {
return false;
}
}

for (Type rhsBound : rhsLowerBounds) {
if (!isAssignableBound(lhsBound, rhsBound)) {
return false;
}
}
}

for (Type lhsBound : lhsLowerBounds) {
for (Type rhsBound : rhsUpperBounds) {
if (!isAssignableBound(rhsBound, lhsBound)) {
return false;
}
}

for (Type rhsBound : rhsLowerBounds) {
if (!isAssignableBound(rhsBound, lhsBound)) {
return false;
}
}
}
} else {
for (Type lhsBound : lhsUpperBounds) {
if (!isAssignableBound(lhsBound, rhsType)) {
return false;
}
}

for (Type lhsBound : lhsLowerBounds) {
if (!isAssignableBound(rhsType, lhsBound)) {
return false;
}
}
}

return true;
}

private static boolean isAssignableBound(Type lhsType, Type rhsType) {
if (rhsType == null) {
return true;
}
if (lhsType == null) {
return false;
}
return isAssignable(lhsType, rhsType);
}
}
Loading