Java Code Examples for com.google.common.primitives.Primitives#isWrapperType()

The following examples show how to use com.google.common.primitives.Primitives#isWrapperType() . 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: 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 2
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 3
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 4
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 5
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 6
Source File: AutoAnnotationProcessor.java    From auto with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the hashCode of the given AnnotationValue, if that hashCode is guaranteed to be always
 * the same. The hashCode of a String or primitive type never changes. The hashCode of a Class or
 * an enum constant does potentially change in different runs of the same program. The hashCode of
 * an array doesn't change if the hashCodes of its elements don't. Although we could have a
 * similar rule for nested annotation values, we currently don't.
 */
private static Optional<Integer> invariableHash(AnnotationValue annotationValue) {
  Object value = annotationValue.getValue();
  if (value instanceof String || Primitives.isWrapperType(value.getClass())) {
    return Optional.of(value.hashCode());
  } else if (value instanceof List<?>) {
    @SuppressWarnings("unchecked") // by specification
    List<? extends AnnotationValue> list = (List<? extends AnnotationValue>) value;
    return invariableHash(list);
  } else {
    return Optional.empty();
  }
}
 
Example 7
Source File: EndpointMeta.java    From ameba with MIT License 5 votes vote down vote up
MessageHandlerFactory(MethodHandle method, ParameterExtractor[] extractors, Class<?> type, long maxMessageSize) {
    this.method = method;
    this.extractors = extractors;
    this.type = Primitives.isWrapperType(type)
            ? type
            : Primitives.wrap(type);
    this.maxMessageSize = maxMessageSize;
}
 
Example 8
Source File: ElVarParamExtension.java    From guice-persist-orient with MIT License 5 votes vote down vote up
private boolean isSafeType(final Class<?> type) {
    boolean res = type.isPrimitive() || Primitives.isWrapperType(type);
    if (!res) {
        for (Class<?> safe : SAFE_TYPES) {
            if (safe.isAssignableFrom(type)) {
                res = true;
                break;
            }
        }
    }
    return res;
}
 
Example 9
Source File: DescriptionHelper.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Helper to convert value to string unless its a char-sequence or primitive/boxed-type.
 *
 * This is to help keep rendering JSON simple, and avoid side-effect with getter invocations when rendering.
 */
private Object convert(final Object value) {
  if (value == null) {
    return null;
  }
  if (value instanceof CharSequence) {
    return value.toString();
  }
  if (value.getClass().isPrimitive() || Primitives.isWrapperType(value.getClass())) {
    return value;
  }
  return String.valueOf(value);
}
 
Example 10
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 11
Source File: UpdateSection.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * Return the object o set by setValue(o) encoded as a JSON string. Return null if o is null
 * or if o is neither a JsonObject nor a String nor a primitive type.
 * @return the JSON string
 */
public String getValue() {
  if (value == null) {
    return null;
  }
  if (value instanceof JsonObject) {
    return ((JsonObject) value).encode();
  }
  if (value instanceof String || value.getClass().isPrimitive() || Primitives.isWrapperType(value.getClass())) {
    return Json.encode(value);
  }
  return null;
}
 
Example 12
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 13
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 14
Source File: BytecodeUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
public static BytecodeNode boxPrimitiveIfNecessary(Scope scope, Class<?> type)
{
    checkArgument(!type.isPrimitive(), "cannot box into primitive type");
    if (!Primitives.isWrapperType(type)) {
        return NOP;
    }
    BytecodeBlock notNull = new BytecodeBlock().comment("box primitive");
    Class<?> expectedCurrentStackType;
    if (type == Long.class) {
        notNull.invokeStatic(Long.class, "valueOf", Long.class, long.class);
        expectedCurrentStackType = long.class;
    }
    else if (type == Double.class) {
        notNull.invokeStatic(Double.class, "valueOf", Double.class, double.class);
        expectedCurrentStackType = double.class;
    }
    else if (type == Boolean.class) {
        notNull.invokeStatic(Boolean.class, "valueOf", Boolean.class, boolean.class);
        expectedCurrentStackType = boolean.class;
    }
    else {
        throw new UnsupportedOperationException("not yet implemented: " + type);
    }

    BytecodeBlock condition = new BytecodeBlock().append(scope.getVariable("wasNull"));

    BytecodeBlock wasNull = new BytecodeBlock()
            .pop(expectedCurrentStackType)
            .pushNull()
            .checkCast(type);

    return new IfStatement()
            .condition(condition)
            .ifTrue(wasNull)
            .ifFalse(notNull);
}
 
Example 15
Source File: LoggerMessageBuilder.java    From godaddy-logger with MIT License 4 votes vote down vote up
protected void buildMessage(Object obj, List<String> path, String currentField) {
    if (currentRecursiveLevel > configs.getRecursiveLevel()) {
        return;
    }

    /**
     * If the custom mapper contains a key that is assignable from obj.getClass() then the function related to the value of the
     * custom mappers key is applied and appended to the builder.
     */
    if (processedCustom(obj, currentField)) {
        return;
    }

    /** If the object is null "=<null>" is appended to show that the object was null in the logs. */
    if (obj == null) {
        processNull(currentField);
    }
    else if (obj instanceof LogMessage) {
        processLogMessage((LogMessage) obj);
    }
    /** If the object is an instance of collection, only the size of the collection is logged. */
    else if (obj instanceof Collection<?>) {
        processCollection(currentField, (Collection) obj);
    }
    else if (obj.getClass().isArray()) {
        processArray(currentField, obj);
    }
    else if (obj instanceof Map) {
        processMap(currentField, (Map) obj);
    }
    /** If the object is an instance of String, the String is wrapped in quotes. */
    else if (obj instanceof String) {
        processString(currentField, (String) obj);
    }
    else if (Primitives.isWrapperType(obj.getClass())) {
        processPrimitive(currentField, obj);
    }
    else if (obj instanceof Enum) {
        processEnum(currentField, obj);
    }
    else {
        processObject(obj, path, currentField);
    }
}
 
Example 16
Source File: BuiltInFunctionTransformer.java    From kylin with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private TupleFilter translateCompareTupleFilter(CompareTupleFilter compTupleFilter) {
    if (compTupleFilter.getFunction() == null
            || (!(compTupleFilter.getFunction() instanceof BuiltInFunctionTupleFilter)))
        return null;

    BuiltInFunctionTupleFilter builtInFunctionTupleFilter = (BuiltInFunctionTupleFilter) compTupleFilter
            .getFunction();

    if (!builtInFunctionTupleFilter.isValid())
        return null;

    TblColRef columnRef = builtInFunctionTupleFilter.getColumn();
    if (columnRef == null) {
        return null;
    }
    Dictionary<?> dict = dimEncMap.getDictionary(columnRef);
    if (dict == null)
        return null;

    CompareTupleFilter translated = new CompareTupleFilter(
            builtInFunctionTupleFilter.isReversed() ? FilterOperatorEnum.NOTIN : FilterOperatorEnum.IN);
    translated.addChild(new ColumnTupleFilter(columnRef));

    try {
        Collection<Object> inValues = Lists.newArrayList();
        for (int i = dict.getMinId(); i <= dict.getMaxId(); i++) {
            Object dictVal = dict.getValueFromId(i);
            Object computedVal = builtInFunctionTupleFilter.invokeFunction(dictVal);
            Class clazz = Primitives.wrap(computedVal.getClass());
            Object targetVal = compTupleFilter.getFirstValue();
            if (Primitives.isWrapperType(clazz))
                targetVal = clazz.cast(clazz.getDeclaredMethod("valueOf", String.class).invoke(null,
                        compTupleFilter.getFirstValue()));

            int comp = ((Comparable) computedVal).compareTo(targetVal);
            boolean compResult = false;
            switch (compTupleFilter.getOperator()) {
            case EQ:
                compResult = comp == 0;
                break;
            case NEQ:
                compResult = comp != 0;
                break;
            case LT:
                compResult = comp < 0;
                break;
            case LTE:
                compResult = comp <= 0;
                break;
            case GT:
                compResult = comp > 0;
                break;
            case GTE:
                compResult = comp >= 0;
                break;
            case IN:
                compResult = compTupleFilter.getValues().contains(computedVal.toString());
                break;
            case NOTIN:
                compResult = !compTupleFilter.getValues().contains(computedVal.toString());
                break;
            default:
                break;
            }
            if (compResult) {
                inValues.add(dictVal);
            }
        }
        translated.addChild(new ConstantTupleFilter(inValues));
    } catch (Exception e) {
        logger.debug(e.getMessage());
        return null;
    }
    return translated;
}
 
Example 17
Source File: SchemaUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static PropertyType getPropertyType( Class<?> klass )
{
    if ( isAssignableFrom( klass, String.class )
        || isAssignableFrom( klass, Character.class )
        || isAssignableFrom( klass, Byte.class ) )
    {
        return PropertyType.TEXT;
    }
    else if ( isAssignableFrom( klass, Integer.class ) )
    {
        return PropertyType.INTEGER;
    }
    else if ( isAssignableFrom( klass, Boolean.class ) )
    {
        return PropertyType.BOOLEAN;
    }
    else if ( isAssignableFrom( klass, Float.class )
        || isAssignableFrom( klass, Double.class ) )
    {
        return PropertyType.NUMBER;
    }
    else if ( isAssignableFrom( klass, Date.class )
        || isAssignableFrom( klass, java.sql.Date.class ) )
    {
        return PropertyType.DATE;
    }
    else if ( isAssignableFrom( klass, Enum.class ) )
    {
        return PropertyType.CONSTANT;
    }
    else if ( isAssignableFrom( klass, IdentifiableObject.class ) )
    {
        return PropertyType.REFERENCE;
    }
    else if ( isAssignableFrom( klass, Collection.class ) )
    {
        return PropertyType.COLLECTION;
    }

    // if klass is primitive (but unknown), fall back to text, if its not then assume reference
    return Primitives.isWrapperType( klass ) ? PropertyType.TEXT : PropertyType.COMPLEX;
}
 
Example 18
Source File: AbstractAnnotatedEndpointMeta.java    From ameba with MIT License 4 votes vote down vote up
protected ParameterExtractor[] getParameterExtractors(final Method method, Map<Integer, Class<?>> unknownParams,
                                                      Set<Class<?>> params, ErrorCollector collector) {
    ParameterExtractor[] result = new ParameterExtractor[method.getParameterTypes().length];
    boolean sessionPresent = false;
    unknownParams.clear();

    for (int i = 0; i < method.getParameterTypes().length; i++) {
        final Class<?> type = method.getParameterTypes()[i];
        final String pathParamName = getPathParamName(method.getParameterAnnotations()[i]);
        if (pathParamName != null) {
            if (!(Primitives.isWrapperType(type) || type.isPrimitive()
                    || type.equals(String.class))) {
                collector.addException(new DeploymentException(
                        LocalizationMessages.ENDPOINT_WRONG_PATH_PARAM(method.getName(), type.getName())));
            }

            result[i] = new ParameterExtractor() {

                final Decoder.Text<?> decoder = getPathParameterDecoder(type);

                @Override
                public Object value(Session session, Object... values) throws DecodeException {
                    Object result = null;

                    if (decoder != null) {
                        result = decoder.decode(session.getPathParameters().get(pathParamName));
                    } else if (type.equals(String.class)) {
                        result = session.getPathParameters().get(pathParamName);
                    }

                    return result;
                }
            };
        } else if (type == Session.class) {
            if (sessionPresent) {
                collector.addException(new DeploymentException(
                        LocalizationMessages.ENDPOINT_MULTIPLE_SESSION_PARAM(method.getName())));
            } else {
                sessionPresent = true;
            }
            result[i] = (session, values) -> session;
        } else if (type == WebSocketSession.class) {
            if (sessionPresent) {
                collector.addException(new DeploymentException(
                        LocalizationMessages.ENDPOINT_MULTIPLE_SESSION_PARAM(method.getName())));
            } else {
                sessionPresent = true;
            }
            result[i] = (session, values) -> {
                Map<String, Object> props = session.getUserProperties();
                StandardWebSocketSession standard = (StandardWebSocketSession) props.get(SESSION_INJECT_KEY);
                if (standard == null) {
                    standard = new StandardWebSocketSession(
                            Requests.getHeaders(),
                            session.getRequestParameterMap(),
                            session.getPathParameters(),
                            session.getUserProperties(),
                            new InetSocketAddress(Requests.getLocalName(), Requests.getLocalPort()),
                            new InetSocketAddress(Requests.getRemoteHost(), Requests.getRemotePort())
                    );
                    standard.initializeNativeSession(session);
                    props.put(SESSION_INJECT_KEY, standard);
                }
                return standard;
            };
        } else if (type == EndpointConfig.class) {
            result[i] = (session, values) -> getEndpointConfig();
        } else if (params.contains(type)) {
            result[i] = (session, values) -> {
                for (Object value : values) {
                    if (value != null && type.isAssignableFrom(value.getClass())) {
                        return value;
                    }
                }

                return null;
            };
        } else {
            unknownParams.put(i, type);
        }
    }

    return result;
}
 
Example 19
Source File: BuiltInFunctionTransformer.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private TupleFilter translateCompareTupleFilter(CompareTupleFilter compTupleFilter) {
    if (compTupleFilter.getFunction() == null
            || (!(compTupleFilter.getFunction() instanceof BuiltInFunctionTupleFilter)))
        return null;

    BuiltInFunctionTupleFilter builtInFunctionTupleFilter = (BuiltInFunctionTupleFilter) compTupleFilter
            .getFunction();

    if (!builtInFunctionTupleFilter.isValid())
        return null;

    TblColRef columnRef = builtInFunctionTupleFilter.getColumn();
    if (columnRef == null) {
        return null;
    }
    Dictionary<?> dict = dimEncMap.getDictionary(columnRef);
    if (dict == null)
        return null;

    CompareTupleFilter translated = new CompareTupleFilter(
            builtInFunctionTupleFilter.isReversed() ? FilterOperatorEnum.NOTIN : FilterOperatorEnum.IN);
    translated.addChild(new ColumnTupleFilter(columnRef));

    try {
        Collection<Object> inValues = Lists.newArrayList();
        for (int i = dict.getMinId(); i <= dict.getMaxId(); i++) {
            Object dictVal = dict.getValueFromId(i);
            Object computedVal = builtInFunctionTupleFilter.invokeFunction(dictVal);
            Class clazz = Primitives.wrap(computedVal.getClass());
            Object targetVal = compTupleFilter.getFirstValue();
            if (Primitives.isWrapperType(clazz))
                targetVal = clazz.cast(clazz.getDeclaredMethod("valueOf", String.class).invoke(null,
                        compTupleFilter.getFirstValue()));

            int comp = ((Comparable) computedVal).compareTo(targetVal);
            boolean compResult = false;
            switch (compTupleFilter.getOperator()) {
            case EQ:
                compResult = comp == 0;
                break;
            case NEQ:
                compResult = comp != 0;
                break;
            case LT:
                compResult = comp < 0;
                break;
            case LTE:
                compResult = comp <= 0;
                break;
            case GT:
                compResult = comp > 0;
                break;
            case GTE:
                compResult = comp >= 0;
                break;
            case IN:
                compResult = compTupleFilter.getValues().contains(computedVal.toString());
                break;
            case NOTIN:
                compResult = !compTupleFilter.getValues().contains(computedVal.toString());
                break;
            default:
                break;
            }
            if (compResult) {
                inValues.add(dictVal);
            }
        }
        translated.addChild(new ConstantTupleFilter(inValues));
    } catch (Exception e) {
        logger.debug(e.getMessage());
        return null;
    }
    return translated;
}
 
Example 20
Source File: ParametricScalarImplementation.java    From presto with Apache License 2.0 4 votes vote down vote up
Parser(String functionName, Method method, Optional<Constructor<?>> constructor)
{
    this.functionName = requireNonNull(functionName, "functionName is null");
    this.nullable = method.getAnnotation(SqlNullable.class) != null;
    checkArgument(nullable || !containsLegacyNullable(method.getAnnotations()), "Method [%s] is annotated with @Nullable but not @SqlNullable", method);

    typeParameters.addAll(Arrays.asList(method.getAnnotationsByType(TypeParameter.class)));

    literalParameters = parseLiteralParameters(method);
    typeParameterNames = typeParameters.stream()
            .map(TypeParameter::value)
            .collect(toImmutableSortedSet(CASE_INSENSITIVE_ORDER));

    SqlType returnType = method.getAnnotation(SqlType.class);
    checkArgument(returnType != null, "Method [%s] is missing @SqlType annotation", method);
    this.returnType = parseTypeSignature(returnType.value(), literalParameters);

    Class<?> actualReturnType = method.getReturnType();
    this.returnNativeContainerType = Primitives.unwrap(actualReturnType);

    if (Primitives.isWrapperType(actualReturnType)) {
        checkArgument(nullable, "Method [%s] has wrapper return type %s but is missing @SqlNullable", method, actualReturnType.getSimpleName());
    }
    else if (actualReturnType.isPrimitive()) {
        checkArgument(!nullable, "Method [%s] annotated with @SqlNullable has primitive return type %s", method, actualReturnType.getSimpleName());
    }

    longVariableConstraints = parseLongVariableConstraints(method);

    this.specializedTypeParameters = getDeclaredSpecializedTypeParameters(method, typeParameters);

    for (TypeParameter typeParameter : typeParameters) {
        checkArgument(
                typeParameter.value().matches("[A-Z][A-Z0-9]*"),
                "Expected type parameter to only contain A-Z and 0-9 (starting with A-Z), but got %s on method [%s]", typeParameter.value(), method);
    }

    inferSpecialization(method, actualReturnType, returnType.value());
    parseArguments(method);

    this.constructorMethodHandle = getConstructor(method, constructor);

    this.methodHandle = getMethodHandle(method);

    this.choice = new ParametricScalarImplementationChoice(nullable, hasConnectorSession, argumentProperties, methodHandle, constructorMethodHandle, dependencies, constructorDependencies);
}