Java Code Examples for com.google.common.reflect.TypeToken#isSupertypeOf()

The following examples show how to use com.google.common.reflect.TypeToken#isSupertypeOf() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClassArgumentConverter.java    From junit5-extensions with MIT License 6 votes vote down vote up
@VisibleForTesting
Class<?> convert(String input, TypeToken<? extends Class<?>> targetType)
    throws ArgumentConversionException {
  Class<?> inputType;
  try {
    inputType = Class.forName(input);
  } catch (ClassNotFoundException e) {
    throw new ArgumentConversionException("Could not convert: " + input, e);
  }

  TypeToken<? extends Class<?>> inputClassType = asClassType(inputType);

  if (!targetType.isSupertypeOf(inputClassType)) {
    throw new ArgumentConversionException(
        String.format("%s is not assignable to %s", inputClassType, targetType));
  }

  return inputType;
}
 
Example 2
Source File: ApiConfigValidator.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private void validateParameterSerializers(ApiParameterConfig config,
    List<Class<? extends Transformer<?, ?>>> serializers, TypeToken<?> parameterType)
    throws ApiParameterConfigInvalidException {
  if (serializers.isEmpty()) {
    return;
  }

  if (serializers.size() > 1) {
    throw new MultipleTransformersException(config, serializers);
  }

  TypeToken<?> sourceType = Serializers.getSourceType(serializers.get(0));
  TypeToken<?> serializedType = Serializers.getTargetType(serializers.get(0));

  if (sourceType == null || serializedType == null) {
    throw new NoTransformerInterfaceException(config, serializers.get(0));
  }

  if (!sourceType.isSupertypeOf(parameterType)) {
    throw new WrongTransformerTypeException(config, serializers.get(0), parameterType,
        sourceType);
  }
}
 
Example 3
Source File: Validator.java    From botbuilder-java with MIT License 5 votes vote down vote up
/**
 * Validates a user provided required parameter to be not null.
 * An {@link IllegalArgumentException} is thrown if a property fails the validation.
 *
 * @param parameter the parameter to validate
 * @throws IllegalArgumentException thrown when the Validator determines the argument is invalid
 */
public static void validate(Object parameter) {
    // Validation of top level payload is done outside
    if (parameter == null) {
        return;
    }

    Class parameterType = parameter.getClass();
    TypeToken<?> parameterToken = TypeToken.of(parameterType);
    if (Primitives.isWrapperType(parameterType)) {
        parameterToken = parameterToken.unwrap();
    }
    if (parameterToken.isPrimitive()
            || parameterType.isEnum()
            || parameterType == Class.class
            || parameterToken.isSupertypeOf(OffsetDateTime.class)
            || parameterToken.isSupertypeOf(ZonedDateTime.class)
            || parameterToken.isSupertypeOf(String.class)
            || parameterToken.isSupertypeOf(Period.class)) {
        return;
    }

    Annotation skipParentAnnotation = parameterType.getAnnotation(SkipParentValidation.class);

    if (skipParentAnnotation == null) {
        for (Class<?> c : parameterToken.getTypes().classes().rawTypes()) {
            validateClass(c, parameter);
        }
    } else {
        validateClass(parameterType, parameter);
    }
}
 
Example 4
Source File: Validator.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
/**
 * Validates a user provided required parameter to be not null.
 * An {@link IllegalArgumentException} is thrown if a property fails the validation.
 *
 * @param parameter the parameter to validate
 * @throws IllegalArgumentException thrown when the Validator determines the argument is invalid
 */
public static void validate(Object parameter) {
    // Validation of top level payload is done outside
    if (parameter == null) {
        return;
    }

    Class parameterType = parameter.getClass();
    TypeToken<?> parameterToken = TypeToken.of(parameterType);
    if (Primitives.isWrapperType(parameterType)) {
        parameterToken = parameterToken.unwrap();
    }
    if (parameterToken.isPrimitive()
            || parameterType.isEnum()
            || parameterType == Class.class
            || parameterToken.isSupertypeOf(LocalDate.class)
            || parameterToken.isSupertypeOf(DateTime.class)
            || parameterToken.isSupertypeOf(String.class)
            || parameterToken.isSupertypeOf(DateTimeRfc1123.class)
            || parameterToken.isSupertypeOf(Period.class)) {
        return;
    }

    Annotation skipParentAnnotation = parameterType.getAnnotation(SkipParentValidation.class);

    if (skipParentAnnotation == null) {
        for (Class<?> c : parameterToken.getTypes().classes().rawTypes()) {
            validateClass(c, parameter);
        }
    } else {
        validateClass(parameterType, parameter);
    }
}
 
Example 5
Source File: Serializers.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private static boolean isSupertypeOf(TypeToken<?> typeToken, List<TypeToken<?>> subtypes) {
  for (TypeToken<?> subType : subtypes) {
    if (typeToken.isSupertypeOf(subType)) {
      return true;
    }
  }
  return false;
}
 
Example 6
Source File: Overlay.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public Overlay() {
    //noinspection UnstableApiUsage
    TypeToken<T> typeToken = new TypeToken<>(getClass()) {
    };
    if (!typeToken.isSupertypeOf(getClass())) {
        throw new RuntimeException("Subclass of Overlay<T> should be castable to T");
    }
}
 
Example 7
Source File: TypeTokenUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenCheckingIsSupertypeOf_shouldReturnFalseIfGenericIsSpecified() throws Exception {
    TypeToken<ArrayList<String>> listString = new TypeToken<ArrayList<String>>() {
    };
    TypeToken<ArrayList<Integer>> integerString = new TypeToken<ArrayList<Integer>>() {
    };

    boolean isSupertypeOf = listString.isSupertypeOf(integerString);

    assertFalse(isSupertypeOf);
}
 
Example 8
Source File: Utils.java    From mobly-bundled-snippets with Apache License 2.0 4 votes vote down vote up
/**
 * Simplified API to invoke an instance method by reflection.
 *
 * <p>Sample usage:
 *
 * <pre>
 *   boolean result = (boolean) Utils.invokeByReflection(
 *           mWifiManager,
 *           "setWifiApEnabled", null /* wifiConfiguration * /, true /* enabled * /);
 * </pre>
 *
 * @param instance Instance of object defining the method to call.
 * @param methodName Name of the method to call. Can be inherited.
 * @param args Variadic array of arguments to supply to the method. Their types will be used to
 *     locate a suitable method to call. Subtypes, primitive types, boxed types, and {@code
 *     null} arguments are properly handled.
 * @return The return value of the method, or {@code null} if no return value.
 * @throws NoSuchMethodException If no suitable method could be found.
 * @throws Throwable The exception raised by the method, if any.
 */
public static Object invokeByReflection(Object instance, String methodName, Object... args)
        throws Throwable {
    // Java doesn't know if invokeByReflection(instance, name, null) means that the array is
    // null or that it's a non-null array containing a single null element. We mean the latter.
    // Silly Java.
    if (args == null) {
        args = new Object[] {null};
    }
    // Can't use Class#getMethod(Class<?>...) because it expects that the passed in classes
    // exactly match the parameters of the method, and doesn't handle superclasses.
    Method method = null;
    METHOD_SEARCHER:
    for (Method candidateMethod : instance.getClass().getMethods()) {
        // getMethods() returns only public methods, so we don't need to worry about checking
        // whether the method is accessible.
        if (!candidateMethod.getName().equals(methodName)) {
            continue;
        }
        Class<?>[] declaredParams = candidateMethod.getParameterTypes();
        if (declaredParams.length != args.length) {
            continue;
        }
        for (int i = 0; i < declaredParams.length; i++) {
            if (args[i] == null) {
                // Null is assignable to anything except primitives.
                if (declaredParams[i].isPrimitive()) {
                    continue METHOD_SEARCHER;
                }
            } else {
                // Allow autoboxing during reflection by wrapping primitives.
                Class<?> declaredClass = Primitives.wrap(declaredParams[i]);
                Class<?> actualClass = Primitives.wrap(args[i].getClass());
                TypeToken<?> declaredParamType = TypeToken.of(declaredClass);
                TypeToken<?> actualParamType = TypeToken.of(actualClass);
                if (!declaredParamType.isSupertypeOf(actualParamType)) {
                    continue METHOD_SEARCHER;
                }
            }
        }
        method = candidateMethod;
        break;
    }
    if (method == null) {
        StringBuilder methodString =
                new StringBuilder(instance.getClass().getName())
                        .append('#')
                        .append(methodName)
                        .append('(');
        for (int i = 0; i < args.length - 1; i++) {
            methodString.append(args[i].getClass().getSimpleName()).append(", ");
        }
        if (args.length > 0) {
            methodString.append(args[args.length - 1].getClass().getSimpleName());
        }
        methodString.append(')');
        throw new NoSuchMethodException(methodString.toString());
    }
    try {
        Object result = method.invoke(instance, args);
        return result;
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}