com.google.common.primitives.Primitives Java Examples

The following examples show how to use com.google.common.primitives.Primitives. 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: AutoAnnotationProcessor.java    From auto with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the wrapper types ({@code Integer.class} etc) that are used in collection parameters
 * like {@code List<Integer>}. This is needed because we will emit a helper method for each such
 * type, for example to convert {@code Collection<Integer>} into {@code int[]}.
 */
private Set<Class<?>> wrapperTypesUsedInCollections(ExecutableElement method) {
  TypeElement javaUtilCollection = elementUtils.getTypeElement(Collection.class.getName());
  ImmutableSet.Builder<Class<?>> usedInCollections = ImmutableSet.builder();
  for (Class<?> wrapper : Primitives.allWrapperTypes()) {
    DeclaredType collectionOfWrapper =
        typeUtils.getDeclaredType(javaUtilCollection, getTypeMirror(wrapper));
    for (VariableElement parameter : method.getParameters()) {
      if (typeUtils.isAssignable(parameter.asType(), collectionOfWrapper)) {
        usedInCollections.add(wrapper);
        break;
      }
    }
  }
  return usedInCollections.build();
}
 
Example #2
Source File: Serialization.java    From monasca-common with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@code node} deserialized to an instance of <T> with the implementation of <T>
 * being selected from the registered targets for the node's root key.
 * 
 * @throws IllegalArgumentException if {@code node} does not contain a single root key
 * @throws IllegalStateException if no target type has been registered for the {@code node}'s root
 *           key
 * @throws RuntimeException if deserialization fails
 */
public static <T> T fromJson(JsonNode node) {
  Preconditions.checkArgument(node.size() == 1, "The node must contain a single root key: %s",
      node);

  String rootKey = node.fieldNames().next();
  @SuppressWarnings("unchecked")
  Class<T> targetType = (Class<T>) targetTypes.get(rootKey);
  if (targetType == null)
    throw new IllegalStateException("No target type is registered for the root key " + rootKey);

  if (targetType.isPrimitive() || Primitives.isWrapperType(targetType)) {
    try {
      return rootMapper.reader(targetType).readValue(node);
    } catch (IOException e) {
      throw Exceptions.uncheck(e, "Failed to deserialize json: {}", node);
    }
  } else {
    T object = Injector.getInstance(targetType);
    injectMembers(object, node);
    return object;
  }
}
 
Example #3
Source File: ArrayReduceFunction.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, Metadata metadata)
{
    Type inputType = boundVariables.getTypeVariable("T");
    Type intermediateType = boundVariables.getTypeVariable("S");
    Type outputType = boundVariables.getTypeVariable("R");
    MethodHandle methodHandle = METHOD_HANDLE.bindTo(inputType);
    return new ScalarFunctionImplementation(
            true,
            ImmutableList.of(
                    valueTypeArgumentProperty(RETURN_NULL_ON_NULL),
                    valueTypeArgumentProperty(USE_BOXED_TYPE),
                    functionTypeArgumentProperty(BinaryFunctionInterface.class),
                    functionTypeArgumentProperty(UnaryFunctionInterface.class)),
            methodHandle.asType(
                    methodHandle.type()
                            .changeParameterType(1, Primitives.wrap(intermediateType.getJavaType()))
                            .changeReturnType(Primitives.wrap(outputType.getJavaType()))));
}
 
Example #4
Source File: ValueTypeInfoFactory.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * A simple type includes no input/output path/data and is either a very simple type (primitives,
 * strings, etc) or one of the supported generic types composed of other simple types.
 */
static boolean isSimpleType(Type type) {
  if (type instanceof Class) {
    Class<?> rawClass = Primitives.wrap((Class<?>) type);
    // These types need no processing for
    return rawClass.equals(String.class)
        || rawClass.equals(Character.class)
        || rawClass.equals(Boolean.class)
        || rawClass.equals(Byte.class)
        || rawClass.equals(Short.class)
        || rawClass.equals(Integer.class)
        || rawClass.equals(Long.class)
        || rawClass.equals(Float.class)
        || rawClass.equals(Double.class)
        || rawClass.equals(OptionalInt.class);
  } else if (type instanceof WildcardType) {
    WildcardType wildcardType = (WildcardType) type;
    Type[] upperBounds = wildcardType.getUpperBounds();
    Preconditions.checkState(upperBounds.length == 1);
    return false;
  }
  return false;
}
 
Example #5
Source File: BuckStarlarkParam.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * @param parameter the parameter type class
 * @param namedParameter the name of the parameter, if any
 * @param defaultSkylarkValue the string represetnation of the default skylark value
 * @param noneable whether this parameter can accept `None`
 * @return an instance of the skylark annotation representing a parameter of the given type and
 *     name
 */
static BuckStarlarkParam fromParam(
    Class<?> parameter,
    @Nullable String namedParameter,
    @Nullable String defaultSkylarkValue,
    boolean noneable) {
  if (namedParameter == null) {
    namedParameter = "";
  }
  if (defaultSkylarkValue == null) {
    defaultSkylarkValue = "";
  }
  Class<?> type = parameter;
  if (type.isPrimitive()) {
    type = Primitives.wrap(type);
  }
  return new BuckStarlarkParam(namedParameter, type, defaultSkylarkValue, noneable);
}
 
Example #6
Source File: TryCastFunction.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, Metadata metadata)
{
    Type fromType = boundVariables.getTypeVariable("F");
    Type toType = boundVariables.getTypeVariable("T");

    Class<?> returnType = Primitives.wrap(toType.getJavaType());

    // the resulting method needs to return a boxed type
    ResolvedFunction resolvedFunction = metadata.getCoercion(fromType, toType);
    MethodHandle coercion = metadata.getScalarFunctionInvoker(resolvedFunction, Optional.empty()).getMethodHandle();
    coercion = coercion.asType(methodType(returnType, coercion.type()));

    MethodHandle exceptionHandler = dropArguments(constant(returnType, null), 0, RuntimeException.class);
    MethodHandle tryCastHandle = catchException(coercion, RuntimeException.class, exceptionHandler);

    boolean nullable = metadata.getFunctionMetadata(resolvedFunction).getArgumentDefinitions().get(0).isNullable();
    List<ArgumentProperty> argumentProperties = ImmutableList.of(nullable ? valueTypeArgumentProperty(USE_BOXED_TYPE) : valueTypeArgumentProperty(RETURN_NULL_ON_NULL));
    return new ScalarFunctionImplementation(true, argumentProperties, tryCastHandle);
}
 
Example #7
Source File: Values.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
/**
 * Determines whether a value is 'true', where true is interpreted depending on the values
 * type.
 */
@SuppressWarnings("rawtypes")
static boolean isTrue(Object v1) {
  if (v1 instanceof Number) {
    // For numbers, compare with  the default value (zero), which we obtain by
    // creating an array.
    return !Array.get(Array.newInstance(Primitives.unwrap(v1.getClass()), 1), 0).equals(v1);
  }
  if (v1 instanceof Boolean) {
    return (Boolean) v1;
  }
  if (v1 instanceof Doc) {
    return !((Doc) v1).isWhitespace();
  }
  if (v1 instanceof String) {
    return !Strings.isNullOrEmpty((String) v1);
  }
  if (v1 instanceof Iterable) {
    return ((Iterable) v1).iterator().hasNext();
  }
  return false;
}
 
Example #8
Source File: RecordConverter.java    From guice-persist-orient with MIT License 6 votes vote down vote up
/**
 * @param result     orient record
 * @param targetType target conversion type
 * @param converter  converter object
 * @param <T>        target conversion type
 * @return converted object
 * @throws ResultConversionException if conversion is impossible
 */
@SuppressWarnings("unchecked")
public <T> T convert(final Object result, final Class<T> targetType, final ResultConverter converter) {
    // wrap primitive, because result will always be object
    final Class<T> target = Primitives.wrap(targetType);
    // do manual conversion to other types if required (usually this will be done automatically by connection
    // object, but async and live callbacks will always return documents)
    T res = tryConversion(result, target);
    if (res != null) {
        return res;
    }

    // use converter
    final ResultDescriptor desc = new ResultDescriptor();
    // support void case for more universal usage
    desc.returnType = target.equals(Void.class) ? ResultType.VOID : ResultType.PLAIN;
    desc.entityType = target;
    desc.expectType = target;
    desc.entityDbType = ORecord.class.isAssignableFrom(target) ? DbType.DOCUMENT : DbType.UNKNOWN;
    res = (T) converter.convert(desc, result);
    ResultUtils.check(res, target);
    return res;
}
 
Example #9
Source File: ContainerFlagField.java    From java-flagz with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected static <X> X itemFromString(String value, Class<X> clazz, Flag flag)
    throws FlagException {
  // In case we get a primitive type (e.g. from Scala), get the boxed version to know
  // how to serialize.
  clazz = Primitives.wrap(clazz);
  if (Number.class.isAssignableFrom(clazz)) {
    return clazz.cast(PrimitiveFlagField.NumberFlagField.fromString(value, clazz, flag));
  } else if (Boolean.class.isAssignableFrom(clazz)) {
    return clazz.cast(Boolean.valueOf(value));
  } else if (String.class.isAssignableFrom(clazz)) {
    return clazz.cast(value);
  } else if (clazz.isEnum()) {
    return (X) PrimitiveFlagField.EnumFlagField.fromString(value, (Class<Enum>) clazz, flag);
  }
  throw new FlagException.UnsupportedType(flag, clazz);
}
 
Example #10
Source File: SupportedTypeIntegrationTest.java    From Akatsuki with Apache License 2.0 6 votes vote down vote up
@Test
public void testBoxedPrimitives() {
	// boxed primitives cannot be null otherwise we get NPE when unboxing
	ImmutableMap<Class<?>, String> defaultValueMap = ImmutableMap.<Class<?>, String> builder()
			.put(Byte.class, "0").put(Short.class, "0").put(Integer.class, "0")
			.put(Long.class, "0L").put(Float.class, "0.0F").put(Double.class, "0.0D")
			.put(Character.class, "\'a\'").put(Boolean.class, "false").build();

	RetainedTestField[] fields = defaultValueMap.entrySet()
			.stream().map(ent -> new RetainedTestField(ent.getKey(),
					"_" + ent.getKey().getSimpleName(), ent.getValue()))
			.toArray(RetainedTestField[]::new);
	// comparison between primitives and boxed primitives does not work,
	// manually wrap it
	testTypes(ALWAYS, (field, type, arguments) -> type.isPrimitive()
			&& field.clazz == Primitives.wrap(type), f->1, fields);

}
 
Example #11
Source File: Tweens.java    From Lemur with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings("unchecked")        
private static Method findMethod( Class type, String name, Object... args ) {
    for( Method m : type.getDeclaredMethods() ) {
        if( !Objects.equals(m.getName(), name) ) {
            continue;
        }
        Class[] paramTypes = m.getParameterTypes();
        if( paramTypes.length != args.length ) {
            continue;
        }
        int matches = 0;
        for( int i = 0; i < args.length; i++ ) {
            if( paramTypes[i].isInstance(args[i]) 
                || Primitives.wrap(paramTypes[i]).isInstance(args[i]) ) {
                matches++;
            }    
        }
        if( matches == args.length ) {
            return m;
        }                
    }
    if( type.getSuperclass() != null ) {
        return findMethod(type.getSuperclass(), name, args);
    }
    return null;
}
 
Example #12
Source File: ScalarFunctionAdapter.java    From presto with Apache License 2.0 6 votes vote down vote up
private static MethodHandle boxedToNullFlagFilter(Class<?> argumentType)
{
    // Start with identity
    MethodHandle handle = identity(argumentType);
    // if argument is a primitive, box it
    if (Primitives.isWrapperType(argumentType)) {
        handle = explicitCastArguments(handle, handle.type().changeParameterType(0, Primitives.unwrap(argumentType)));
    }
    // Add boolean null flag
    handle = dropArguments(handle, 1, boolean.class);
    // if flag is true, return null, otherwise invoke identity
    return guardWithTest(
            isTrueNullFlag(handle.type(), 0),
            returnNull(handle.type()),
            handle);
}
 
Example #13
Source File: JGivenMethodRule.java    From JGiven with Apache License 2.0 6 votes vote down vote up
private static List<Object> getTypeMatchingValuesInOrderOf( Class<?>[] expectedClasses, List<Object> values ) {
    List<Object> valuesCopy = Lists.newArrayList( values );
    List<Object> result = new ArrayList<Object>();
    for( Class<?> argumentClass : expectedClasses ) {
        for( Iterator<Object> iterator = valuesCopy.iterator(); iterator.hasNext(); ) {
            Object value = iterator.next();
            if( Primitives.wrap( argumentClass ).isInstance( value ) ) {
                result.add( value );
                iterator.remove();
                break;
            }
        }
    }
    if( result.size() < expectedClasses.length ) {
        log.warn( format( "Couldn't find matching values in '%s' for expected classes '%s',", valuesCopy,
            Arrays.toString( expectedClasses ) ) );
    }
    return result;
}
 
Example #14
Source File: MethodMatcher.java    From business with Mozilla Public License 2.0 6 votes vote down vote up
private static boolean checkParameterTypes(Type[] parameterTypes, Object[] args) {
    for (int i = 0; i < args.length; i++) {
        Object object = args[i];
        Type parameterType = parameterTypes[i];
        if (object != null) {
            Class<?> objectType = object.getClass();
            Class<?> unWrapPrimitive = null;
            if (Primitives.isWrapperType(objectType)) {
                unWrapPrimitive = Primitives.unwrap(objectType);
            }
            if (!(((Class<?>) parameterType).isAssignableFrom(
                    objectType) || (unWrapPrimitive != null && ((Class<?>) parameterType).isAssignableFrom(
                    unWrapPrimitive)))) {
                return false;
            }
        }
    }
    return true;
}
 
Example #15
Source File: ExpressionInterpreter.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
protected Object visitLambdaExpression(LambdaExpression node, Object context)
{
    if (optimize) {
        // TODO: enable optimization related to lambda expression
        // A mechanism to convert function type back into lambda expression need to exist to enable optimization
        return node;
    }

    Expression body = node.getBody();
    List<String> argumentNames = node.getArguments().stream()
            .map(LambdaArgumentDeclaration::getName)
            .map(Identifier::getValue)
            .collect(toImmutableList());
    FunctionType functionType = (FunctionType) expressionTypes.get(NodeRef.<Expression>of(node));
    checkArgument(argumentNames.size() == functionType.getArgumentTypes().size());

    return generateVarArgsToMapAdapter(
            Primitives.wrap(functionType.getReturnType().getJavaType()),
            functionType.getArgumentTypes().stream()
                    .map(Type::getJavaType)
                    .map(Primitives::wrap)
                    .collect(toImmutableList()),
            argumentNames,
            map -> process(body, new LambdaSymbolResolver(map)));
}
 
Example #16
Source File: BuiltInFunctionTupleFilter.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public void addChild(TupleFilter child) {
    if (child instanceof ColumnTupleFilter || child instanceof BuiltInFunctionTupleFilter) {
        columnContainerFilter = child;
        colPosition = methodParams.size();
        methodParams.add(null);
    } else if (child instanceof ConstantTupleFilter) {
        this.constantTupleFilter = (ConstantTupleFilter) child;
        Serializable constVal = (Serializable) child.getValues().iterator().next();
        try {
            constantPosition = methodParams.size();
            Class<?> clazz = Primitives.wrap(method.getParameterTypes()[methodParams.size()]);
            if (!Primitives.isWrapperType(clazz))
                methodParams.add(constVal);
            else
                methodParams.add((Serializable) clazz
                        .cast(clazz.getDeclaredMethod("valueOf", String.class).invoke(null, constVal)));
        } catch (Exception e) {
            logger.warn("Reflection failed for methodParams. ", e);
            isValidFunc = false;
        }
    }
    super.addChild(child);
}
 
Example #17
Source File: ValueBuffer.java    From presto with Apache License 2.0 6 votes vote down vote up
private static Object normalizeValue(Type type, @Nullable Object value)
{
    if (value == null) {
        return value;
    }

    Class<?> javaType = type.getJavaType();
    if (javaType.isPrimitive()) {
        checkArgument(Primitives.wrap(javaType).isInstance(value), "Type %s incompatible with %s", type, value);
        return value;
    }
    if (javaType == Slice.class) {
        if (value instanceof Slice) {
            return value;
        }
        if (value instanceof String) {
            return utf8Slice(((String) value));
        }
        if (value instanceof byte[]) {
            return wrappedBuffer((byte[]) value);
        }
    }
    throw new IllegalArgumentException(format("Type %s incompatible with %s", type, value));
}
 
Example #18
Source File: AnnotatedConfig.java    From selenium with Apache License 2.0 6 votes vote down vote up
private String getSingleValue(Object value) {
  if (value == null) {
    return null;
  }

  if (value instanceof Map) {
    throw new ConfigException("Map fields may not be used for configuration: " + value);
  }

  if (value instanceof Collection) {
    throw new ConfigException("Collection fields may not be used for configuration: " + value);
  }

  if (Boolean.FALSE.equals(value) && !Primitives.isWrapperType(value.getClass())) {
    return null;
  }

  if (value instanceof Number && ((Number) value).floatValue() == 0f) {
    return null;
  }

  return String.valueOf(value);
}
 
Example #19
Source File: PrimitiveOptionalPropertyTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
<T, P extends Number> OptionalFactory(
    Class<T> type,
    Class<P> primitiveType,
    IntFunction<P> examples) {
  this.type = type;
  this.primitiveType = primitiveType;
  this.boxedType = Primitives.wrap(primitiveType);
  this.examples = examples;
}
 
Example #20
Source File: TypeToken.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns the corresponding wrapper type if this is a primitive type; otherwise returns
 * {@code this} itself. Idempotent.
 *
 * @since 15.0
 */


public final TypeToken<T> wrap() {
  if (isPrimitive()) {
    @SuppressWarnings("unchecked") // this is a primitive class
    Class<T> type = (Class<T>) runtimeType;
    return of(Primitives.wrap(type));
  }
  return this;
}
 
Example #21
Source File: GenericTypeHelper.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if a value of a particular type (from) is assignable to a field of
 * a particular type (to). Also allows assigning wrapper types to primitive
 * types.
 *
 * <p>The checks done here should be identical to the checks done by
 * {@link java.lang.reflect.Field#set}. I.e., if this method returns true, a
 * subsequent call to {@link java.lang.reflect.Field#set} should succeed.
 */
public static boolean isAssignableFrom(Type to, Type from) {
  if (to instanceof Class<?>) {
    Class<?> toClass = (Class<?>) to;
    if (toClass.isPrimitive()) {
      return Primitives.wrap(toClass).equals(from);
    }
  }
  return TypeToken.of(to).isSupertypeOf(from);
}
 
Example #22
Source File: TypeToken.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns the corresponding primitive type if this is a wrapper type; otherwise returns
 * {@code this} itself. Idempotent.
 *
 * @since 15.0
 */


public final TypeToken<T> unwrap() {
  if (isWrapper()) {
    @SuppressWarnings("unchecked") // this is a wrapper class
    Class<T> type = (Class<T>) runtimeType;
    return of(Primitives.unwrap(type));
  }
  return this;
}
 
Example #23
Source File: NbtFactory.java    From AdditionsAPI with MIT License 5 votes vote down vote up
/**
 * Retrieve the nearest NBT type for a given primitive type.
 * @param primitive - the primitive type.
 * @return The corresponding type.
 */
private NbtType getPrimitiveType(Object primitive) {
    NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get(
        Primitives.unwrap(primitive.getClass())
    ));
    
    // Display the illegal value at least
    if (type == null)
        throw new IllegalArgumentException(String.format(
            "Illegal type: %s (%s)", primitive.getClass(), primitive));
    return type;
}
 
Example #24
Source File: DiffUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a formatted listing of Set contents, using a single line format if all elements are
 * wrappers of primitive types or Strings, and a multiline (one object per line) format if they
 * are not.
 */
private static String formatSetContents(Set<?> set) {
  for (Object obj : set) {
    if (!Primitives.isWrapperType(obj.getClass()) && !(obj instanceof String)) {
      return "\n        " + Joiner.on(",\n        ").join(set);
    }
  }
  return " " + set;
}
 
Example #25
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 #26
Source File: Whitebox.java    From hugegraph-common with Apache License 2.0 5 votes vote down vote up
public static <T> T invoke(Class<?> clazz, String methodName,
                           Object self, Object... args) {
    Class<?>[] classes = new Class<?>[args.length];
    int i = 0;
    for (Object arg : args) {
        E.checkArgument(arg != null, "The argument can't be null");
        classes[i++] = Primitives.unwrap(arg.getClass());
    }
    return invoke(clazz, classes, methodName, self, args);
}
 
Example #27
Source File: TypeToken.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns the corresponding wrapper type if this is a primitive type; otherwise returns
 * {@code this} itself. Idempotent.
 *
 * @since 15.0
 */


public final TypeToken<T> wrap() {
  if (isPrimitive()) {
    @SuppressWarnings("unchecked") // this is a primitive class
    Class<T> type = (Class<T>) runtimeType;
    return of(Primitives.wrap(type));
  }
  return this;
}
 
Example #28
Source File: TypeToken.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns the corresponding primitive type if this is a wrapper type; otherwise returns
 * {@code this} itself. Idempotent.
 *
 * @since 15.0
 */


public final TypeToken<T> unwrap() {
  if (isWrapper()) {
    @SuppressWarnings("unchecked") // this is a wrapper class
    Class<T> type = (Class<T>) runtimeType;
    return of(Primitives.unwrap(type));
  }
  return this;
}
 
Example #29
Source File: ResultAnalyzer.java    From guice-persist-orient with MIT License 5 votes vote down vote up
private static Class<?> resolveExpectedType(final Class<?> returnClass, final Class<?> returnCollectionType) {
    final Class<?> expected;
    if (returnCollectionType != null) {
        check(returnClass.isAssignableFrom(returnCollectionType),
                "Requested collection %s is incompatible with method return type %s",
                returnCollectionType, returnClass);
        expected = returnCollectionType;
    } else {
        expected = returnClass;
    }
    // wrap primitive, because result will always be object
    return Primitives.wrap(expected);
}
 
Example #30
Source File: ReflectionUtil.java    From NOVA-Core with GNU Lesser General Public License v3.0 5 votes vote down vote up
static float calculateDistance(Class<?> a, Class<?> b) {
	float cost = 0F;
	if (b.isPrimitive()) {
		b = Primitives.wrap(b);
		if (!a.isPrimitive()) {
			cost += 0.1F; // Penalty for unwrapping
		}
		a = Primitives.wrap(a);

		cost += calculateDistancePrimitive(a, b);
		return cost;
	} else {
		while (a != null && !a.equals(b)) {
			if (a.isInterface() && a.isAssignableFrom(b)) {
				// Interface match
				cost += 0.25F;
				break;
			}
			cost++;
			a = a.getSuperclass();
		}
		if (a == null) {
			// Object match
			cost += 1.5F;
		}
	}
	return cost;
}