List of usage examples for com.google.common.reflect TypeToken isSupertypeOf
public final boolean isSupertypeOf(Type type)
From source file:com.amitinside.java8.practice.guava.reflection.Reflection.java
public static void main(final String[] args) throws NoSuchMethodException, SecurityException { final List<String> stringList = Lists.newArrayList(); final List<Integer> intList = Lists.newArrayList(); System.out.println(stringList.getClass().isAssignableFrom(intList.getClass())); // returns true, even though ArrayList<String> is not assignable from // ArrayList<Integer> TypeToken.of(String.class); TypeToken.of(Integer.class); final TypeToken<List<String>> stringListTok = new TypeToken<List<String>>() { };// ww w. j a v a2 s .c o m final TypeToken<List<Integer>> integerListTok = new TypeToken<List<Integer>>() { }; System.out.println(stringListTok.isSupertypeOf(integerListTok)); final Candidate candidate = new Candidate("AMIT"); final Method getMethod = Arrays.stream(candidate.getClass().getMethods()) .filter(method -> method.isAnnotationPresent(Nullable.class)).findFirst().get(); final Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() { }.method(getMethod); System.out.println(invokable.isStatic()); }
From source file:com.google.api.server.spi.config.model.Serializers.java
private static boolean isSupertypeOf(TypeToken<?> typeToken, List<TypeToken<?>> subtypes) { for (TypeToken<?> subType : subtypes) { if (typeToken.isSupertypeOf(subType)) { return true; }//w w w . j av a 2s . c o m } return false; }
From source file:org.tensorics.core.tree.walking.Trees.java
@SuppressWarnings("unchecked") private static <T> T findFirstNodeOfType(List<Node> currentPath, TypeToken<T> nodeToken) { for (Node actualCheckedNode : currentPath) { if (nodeToken.isSupertypeOf(actualCheckedNode.getClass())) { return (T) actualCheckedNode; }/*from w w w .ja va 2s .co m*/ } return null; }
From source file:com.google.android.mobly.snippet.bundled.utils.Utils.java
/** * Simplified API to invoke an instance method by reflection. * * <p>Sample usage:/* w ww .ja v a 2 s.c o m*/ * * <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(); } }
From source file:com.google.api.server.spi.config.annotationreader.ApiAnnotationIntrospector.java
/** * Gets the schema type for a type. The schema type is identical to the original type if * there is no matching {@link com.google.api.server.spi.config.ApiTransformer} annotation for * the type. If there is a {@link com.google.api.server.spi.config.ResourceTransformer} installed, * the source type determines schema, not the output map. *///from w ww . jav a2 s .c o m public static TypeToken<?> getSchemaType(TypeToken<?> type, ApiConfig config) { Type rawType = type.getType(); if (rawType instanceof Class || rawType instanceof ParameterizedType) { List<Class<? extends Transformer<?, ?>>> serializers = Serializers.getSerializerClasses(type, config.getSerializationConfig()); if (!serializers.isEmpty() && !(ResourceTransformer.class.isAssignableFrom(serializers.get(0)))) { TypeToken<?> sourceType = Serializers.getSourceType(serializers.get(0)); TypeToken<?> serializedType = Serializers.getTargetType(serializers.get(0)); Preconditions.checkArgument(sourceType.isSupertypeOf(type), "Serializer specified for %s, but only serializes for %s: %s", type, sourceType, serializers.get(0)); Preconditions.checkArgument(serializedType != null, "Couldn't find Serializer interface in serializer for %s: %s", type, serializers.get(0)); return serializedType; } } return type; }
From source file:com.google.errorprone.refaster.UTemplater.java
/** * Similar to {@link Class#asSubclass(Class)}, but it accepts a {@link TypeToken} so it handles * generics better./* w w w. j ava 2 s . c om*/ */ @SuppressWarnings("unchecked") private static <T> Class<? extends T> asSubclass(Class<?> klass, TypeToken<T> token) throws ClassCastException { if (!token.isSupertypeOf(klass)) { throw new ClassCastException(klass + " is not assignable to " + token); } return (Class<? extends T>) klass; }
From source file:org.dcache.pool.movers.AbstractMover.java
public AbstractMover(ReplicaDescriptor handle, PoolIoFileMessage message, CellPath pathToDoor, TransferService<M> transferService, ChecksumModule checksumModule) { TypeToken<M> type = new TypeToken<M>(getClass()) { };//from ww w . j av a2s . c o m checkArgument(type.isSupertypeOf(getClass())); _queue = message.getIoQueueName(); _protocolInfo = (P) message.getProtocolInfo(); _initiator = message.getInitiator(); _isPoolToPoolTransfer = message.isPool2Pool(); _ioMode = (message instanceof PoolAcceptFileMessage) ? FileStore.O_RW : FileStore.O_READ; _subject = message.getSubject(); _id = message.getId(); _billingPath = message.getBillingPath(); _transferPath = message.getTransferPath(); _pathToDoor = pathToDoor; _handle = handle; _transferService = transferService; }
From source file:com.google.api.server.spi.config.validation.ApiConfigValidator.java
private void validateParameterSerializers(ApiParameterConfig config, List<Class<? extends Transformer<?, ?>>> serializers, TypeToken<?> parameterType) throws ApiParameterConfigInvalidException { if (serializers.isEmpty()) { return;//ww w .j a v a2 s . c o m } 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); } }