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

The following examples show how to use com.google.common.reflect.TypeToken#isAssignableFrom() . 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: Types.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Test if an invocation conversion can be applied to the given types.
 *
 * https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.3
 */
public static boolean isConvertibleForInvocation(TypeToken<?> to, TypeToken<?> from) {
    if(to.isPrimitive()) {
        // Assigning to a primitive allows for both unboxing and primitive widening
        Class<?> fromRaw = from.getRawType();
        if(!fromRaw.isPrimitive()) {
            fromRaw = BOXINGS.inverse().get(fromRaw);
            if(fromRaw == null) return false;
        }
        return isPromotable(to.getRawType(), fromRaw);
    } else if(from.isPrimitive()) {
        // Assigning to an object from a primitive allows boxing and reference widening
        return to.isAssignableFrom(box(from.getRawType()));
    } else {
        return to.isAssignableFrom(from);
    }
}
 
Example 2
Source File: Queue.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
private TypeToken<? extends Message> getMessageType(TypeToken decl, Method method) {
    if(method.getParameterTypes().length < 1 || method.getParameterTypes().length > 3) {
        throw new IllegalStateException("Message handler method must take 1 to 3 parameters");
    }

    final TypeToken<Message> base = new TypeToken<Message>(){};

    for(Type param : method.getGenericParameterTypes()) {
        final TypeToken paramToken = decl.resolveType(param);
        Types.assertFullySpecified(paramToken);
        if(base.isAssignableFrom(paramToken)) {
            messageRegistry.typeName(paramToken.getRawType()); // Verify message type is registered
            return paramToken;
        }
    }

    throw new IllegalStateException("Message handler has no message parameter");
}
 
Example 3
Source File: ValueResolver.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
<S> ValueResolver<S> cloneReplacingValueAndType(Object newValue, TypeToken<S> superType) {
    // superType expected to be either type or Object.class
    if (!superType.isAssignableFrom(typeT)) {
        throw new IllegalStateException("superType must be assignable from " + typeT);
    }
    ValueResolver<S> result = new ValueResolver<S>(newValue, superType)
        .context(exec).description(description)
        .embedResolutionInTask(embedResolutionInTask)
        .deep(forceDeep, deepTraversalUsesRootType)
        .timeout(timeout)
        .immediately(immediately)
        .recursive(recursive);
    if (returnDefaultOnGet) {
        if (!superType.getRawType().isInstance(defaultValue)) {
            throw new IllegalStateException("Existing default value " + defaultValue + " not compatible with new type " + superType);
        }
        @SuppressWarnings("unchecked")
        S typedDefaultValue = (S)defaultValue;
        result.defaultValue(typedDefaultValue);
    }
    if (swallowExceptions) result.swallowExceptions();
    return result;
}
 
Example 4
Source File: BasicSpecParameter.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private static Object tryToImmutable(Object val, TypeToken<?> type) {
    Object result;
    if (Set.class.isAssignableFrom(type.getRawType()) && val instanceof Iterable) {
        result = Collections.unmodifiableSet(MutableSet.copyOf((Iterable<?>)val));
    } else if (val instanceof Iterable) {
        result = Collections.unmodifiableList(MutableList.copyOf((Iterable<?>)val));
    } else if (val instanceof Map) {
        result = Collections.unmodifiableMap(MutableMap.copyOf((Map<?, ?>)val));
    } else {
        return val;
    }
    
    if (type != null && !type.isAssignableFrom(result.getClass())) {
        log.warn("Unable to convert parameter default value (type "+type+") to immutable");
        return val;
    } else {
        return result;
    }
}
 
Example 5
Source File: AbstractConfigMapImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private static TypeToken<?> moreSpecificOrWarningPreferringFirst(ConfigKey<?> ownKey, ConfigKey<?> queryKey, String context) {
    if (ownKey==null && queryKey==null) return null;
    if (queryKey==null) return ownKey.getTypeToken();
    if (ownKey==null) return queryKey.getTypeToken();
    
    TypeToken<?> ownType = ownKey.getTypeToken();
    TypeToken<?> queryType = queryKey.getTypeToken();
    if (queryType.isAssignableFrom(ownType)) {
        // own type is same or more specific, normal path
        return ownType;
    }
    if (ownType.isAssignableFrom(queryType)) {
        // query type is more specific than type defined; unusual but workable
        LOG.debug("Query for "+queryKey+" wants more specific type than key "+ownKey+" declared on "+context+" (unusual but clear what to do)");
        // previously (to 2017-11) we used the less specific type, only issue noticed was if an anonymous key is persisted
        // ie so a non-declared key before rebind becomes a declared key afterwards.  we're going to fix that also.
        return queryType;
    }
    // types are incompatible - continue previous behaviour of preferring own key, but warn
    LOG.warn("Query for "+queryKey+" on "+context+" matched incompatible declared type in key "+ownKey+"; using the declared type");
    return ownType;
}
 
Example 6
Source File: MinimalSupertypeSet.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected boolean prune(TypeToken<? super T> adding) {
    for(Iterator<TypeToken<? super T>> iterator = iterator(); iterator.hasNext(); ) {
        final TypeToken<? super T> existing = iterator.next();
        if(adding.isAssignableFrom(existing)) return false;
        if(existing.isAssignableFrom(adding)) iterator.remove();
    }
    return true;
}
 
Example 7
Source File: MathAggregatorFunctions.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public AbstractComputingNumber(Number defaultValueForUnreportedSensors, Number valueToReportIfNoSensors, TypeToken<T> typeToken) {
    this.defaultValueForUnreportedSensors = defaultValueForUnreportedSensors;
    this.valueToReportIfNoSensors = valueToReportIfNoSensors;
    if (typeToken != null && TypeToken.of(Number.class).isAssignableFrom(typeToken.getType())) {
        this.typeToken = typeToken;
    } else if (typeToken == null || typeToken.isAssignableFrom(Number.class)) {
        // use double if e.g. Object is supplied
        this.typeToken = (TypeToken)TypeToken.of(Double.class);
    } else {
        throw new IllegalArgumentException("Type "+typeToken+" is not valid for "+this);
    }
}
 
Example 8
Source File: Enrichers.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public ComputingNumber(Number defaultValueForUnreportedSensors, Number valueToReportIfNoSensors, TypeToken<T> typeToken) {
    this.defaultValueForUnreportedSensors = defaultValueForUnreportedSensors;
    this.valueToReportIfNoSensors = valueToReportIfNoSensors;
    if (typeToken!=null && TypeToken.of(Number.class).isAssignableFrom(typeToken.getType())) {
        this.typeToken = typeToken;
    } else if (typeToken==null || typeToken.isAssignableFrom(Number.class)) {
        // use double if e.g. Object is supplied
        this.typeToken = (TypeToken)TypeToken.of(Double.class);
    } else {
        throw new IllegalArgumentException("Type "+typeToken+" is not valid for "+this);
    }
}
 
Example 9
Source File: Enrichers.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public ComputingIsQuorate(TypeToken<T> typeToken, QuorumCheck quorumCheck, int totalSize) {
    this.quorumCheck = quorumCheck;
    this.totalSize = totalSize;

    if (typeToken!=null && TypeToken.of(Boolean.class).isAssignableFrom(typeToken.getType())) {
        this.typeToken = typeToken;
    } else if (typeToken==null || typeToken.isAssignableFrom(Boolean.class)) {
        this.typeToken = (TypeToken)TypeToken.of(Boolean.class);
    } else {
        throw new IllegalArgumentException("Type " + typeToken + " is not valid for " + this + " -- expected " + TypeToken.of(Boolean.class));
    }
}
 
Example 10
Source File: UTemplater.java    From Refaster with Apache License 2.0 5 votes vote down vote up
/**
 * Similar to {@link Class#asSubclass(Class)}, but it accepts a {@link TypeToken} so it handles
 * generics better.
 */
@SuppressWarnings("unchecked")
private <T> Class<? extends T> asSubclass(Class<?> klass, TypeToken<T> token)
    throws ClassCastException{
  if (!token.isAssignableFrom(klass)) {
    throw new ClassCastException(klass + " is not assignable to " + token);
  }
  return (Class<? extends T>) klass;
}
 
Example 11
Source File: Types.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Predicate<? super Type> assignableTo(final Type to) {
    final TypeToken<?> toToken = TypeToken.of(to);
    return from -> from != null && toToken.isAssignableFrom(from);
}
 
Example 12
Source File: Fields.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
private static Field assertAssignableTo(Field field, TypeToken<?> type) {
    if(!type.isAssignableFrom(TypeToken.of(field.getGenericType()))) {
        throw new NoSuchFieldError("Field " + field.getName() + " is not of type " + type);
    }
    return field;
}
 
Example 13
Source File: Fields.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Predicate<Field> assignableTo(TypeToken<?> type) {
    return field -> type.isAssignableFrom(field.getGenericType());
}
 
Example 14
Source File: Transaction.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
private Transaction(Exchange.Direct exchange,
                    final Queue replyQueue,
                    Message request,
                    @Nullable Metadata requestProps,
                    @Nullable Publish publish,
                    TypeToken<T> replyType,
                    @Nullable Duration timeout) {

    super(timeout != null ? timeout : DEFAULT_TIMEOUT);

    checkNotNull(request, "request");
    checkNotNull(replyType, "replyType");

    this.callSite = new Exception().getStackTrace();
    this.replyQueue = replyQueue;

    final Metadata finalRequestProps = requestProps = replyQueue.client().getProperties(request, requestProps);
    finalRequestProps.setReplyTo(this.replyQueue.name());

    this.requestId = checkNotNull(finalRequestProps.getMessageId());
    this.requestType = request.getClass();

    this.messageHandler = new MessageHandler<Message>() {
        @Override public void handleDelivery(Message message, TypeToken<? extends Message> type, Metadata replyProps, Delivery delivery) {
            if(requestId.equals(replyProps.getCorrelationId())) {
                Transaction.this.replyQueue.unsubscribe(messageHandler);

                if(replyProps.protocolVersion() != finalRequestProps.protocolVersion()) {
                    setException(new ApiException("Received a protocol " + replyProps.protocolVersion() +
                                                  " reply to a protocol " + finalRequestProps.protocolVersion() + " request",
                                                  callSite));
                } else {
                    final Reply reply = message instanceof Reply ? (Reply) message : null;
                    if(reply != null && !reply.success()) {
                        setException(new ApiException(reply.error() != null ? reply.error()
                                                                            : "Generic failure reply to request " + requestId,
                                                      callSite));
                    } else if(!replyType.isAssignableFrom(type)) {
                        setException(new ApiException("Wrong reply type to request " + requestId +
                                                      ", expected a " + replyType +
                                                      ", received a " + type,
                                                      callSite));
                    } else {
                        set((T) message);
                    }
                }
            }
        }
    };

    this.replyQueue.subscribe(Message.class, messageHandler, null);

    exchange.publishAsync(request, finalRequestProps, publish);
}