Java Code Examples for java.lang.reflect.Type#equals()

The following examples show how to use java.lang.reflect.Type#equals() . 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: JSON.java    From director-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Deserialize the given JSON string to Java object.
 *
 * @param <T>        Type
 * @param body       The JSON string
 * @param returnType The type to deserialize into
 * @return The deserialized Java object
 */
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
    try {
        if (isLenientOnJson) {
            JsonReader jsonReader = new JsonReader(new StringReader(body));
            // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
            jsonReader.setLenient(true);
            return gson.fromJson(jsonReader, returnType);
        } else {
            return gson.fromJson(body, returnType);
        }
    } catch (JsonParseException e) {
        // Fallback processing when failed to parse JSON form response body:
        // return the response body string directly for the String return type;
        if (returnType.equals(String.class))
            return (T) body;
        else throw e;
    }
}
 
Example 2
Source File: ComponentGraph.java    From vespa with Apache License 2.0 6 votes vote down vote up
private Object handleParameter(Node node, Injector fallbackInjector, Pair<Type, List<Annotation>> annotatedParameterType) {
    Type parameterType = annotatedParameterType.getFirst();
    List<Annotation> annotations = annotatedParameterType.getSecond();

    if (parameterType instanceof Class && parameterType.equals(ComponentId.class)) {
        return node.componentId();
    } else if (parameterType instanceof Class && ConfigInstance.class.isAssignableFrom((Class<?>) parameterType)) {
        return handleConfigParameter((ComponentNode) node, (Class<?>) parameterType);
    } else if (parameterType instanceof ParameterizedType
            && ((ParameterizedType) parameterType).getRawType().equals(ComponentRegistry.class)) {
        ParameterizedType registry = (ParameterizedType) parameterType;
        return getComponentRegistry(registry.getActualTypeArguments()[0]);
    } else if (parameterType instanceof Class) {
        return handleComponentParameter(node, fallbackInjector, (Class<?>) parameterType, annotations);
    } else if (parameterType instanceof ParameterizedType) {
        throw new RuntimeException("Injection of parameterized type " + parameterType + " is not supported.");
    } else {
        throw new RuntimeException("Injection of type " + parameterType + " is not supported");
    }
}
 
Example 3
Source File: GenericsUtils.java    From redisq with MIT License 6 votes vote down vote up
/**
 * Fetches the declared type on a specific interface implemented by the provided class.
 * @param clazz the class on which implemented interfaces will be looked upon
 * @param specificInterface the interface to look for
 * @return the generic type implemented for the provided interface, or null if not found.
 */
public static Class<?> getGenericTypeOfInterface(Class<?> clazz, Class<?> specificInterface) {
    Type[] genericInterfaces = clazz.getGenericInterfaces();
    if (genericInterfaces != null) {
        for (Type genericType : genericInterfaces) {
            if (genericType instanceof ParameterizedType) {
                Type rawType = ((ParameterizedType) genericType).getRawType();
                if (rawType.equals(specificInterface)) {
                    ParameterizedType paramType = (ParameterizedType) genericType;
                    return (Class<?>) paramType.getActualTypeArguments()[0];
                }
            }
        }
    }
    return null;
}
 
Example 4
Source File: JSON.java    From huaweicloud-cs-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Deserialize the given JSON string to Java object.
 *
 * @param <T>        Type
 * @param body       The JSON string
 * @param returnType The type to deserialize into
 * @return The deserialized Java object
 */
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
    try {
        if (isLenientOnJson) {
            JsonReader jsonReader = new JsonReader(new StringReader(body));
            // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
            jsonReader.setLenient(true);
            return gson.fromJson(jsonReader, returnType);
        } else {
            return gson.fromJson(body, returnType);
        }
    } catch (JsonParseException e) {
        // Fallback processing when failed to parse JSON form response body:
        // return the response body string directly for the String return type;
        if (returnType.equals(String.class))
            return (T) body;
        else throw (e);
    }
}
 
Example 5
Source File: OptionalMockery.java    From Mockery with Apache License 2.0 6 votes vote down vote up
/**
 * Return empty if type is String, 0 if it is a number, and otherwise return a null reference.
 */
private Object legalOrIllegal(Metadata<Optional> metadata) {
  Type type = metadata.getType();

  if (type.equals(String.class)) {
    return safetyCast.with("", type);
  }

  for (Type numericType : SupportedTypes.NUMERIC) {
      if (type.equals(numericType)) {
        return safetyCast.with(0, type);
      }
  }

  return null;
}
 
Example 6
Source File: ComparatorTypesVisitor.java    From generics-resolver with MIT License 6 votes vote down vote up
/**
 * Check lower bounded wildcard cases. Method is not called if upper bounds are not equal.
 * <p>
 * If right is not lower wildcard - no matter what left is - it's always more specific.
 * <p>
 * If right is lower wildcard and left is simple class then right could be more specific only when left is Object.
 * Note that in this case left could be not Object as any type is more specific then Object (lower wildcard upper
 * bound).
 * <p>
 * When both lower wildcards: lower bounds must be from one hierarchy and left type should be lower.
 * For example,  ? super Integer and ? super BigInteger are not assignable in spite of the fact that they
 * share some common types. ? super Number is more specific then ? super Integer (super inverse meaning).
 *
 * @param one first type
 * @param two second type
 * @return true when left is more specific, false otherwise
 */
private boolean compareLowerBounds(final Type one, final Type two) {
    final boolean res;
    // ? super Object is impossible here due to types cleanup in tree walker
    if (notLowerBounded(two)) {
        // ignore possible left lower bound when simple type on the right (not Object - root condition above)
        res = true;
        // if left type is wildcard they are not equal (super Object case already prevented)
        equal = equal && (notLowerBounded(one) || ((WildcardType) one).getLowerBounds()[0] == Object.class);
    } else if (notLowerBounded(one)) {
        // special case: left is Object and right is lower bounded wildcard
        // e.g Object and ? super String (last is more specific, while it's upper bound is Object too)
        // otherwise, any non Object is more specific
        res = one != Object.class;
        // two is lower bounded and one is not - can't be equal (super Object case already prevented)
        equal = equal && ((WildcardType) two).getLowerBounds()[0] == Object.class;
    } else {
        final Type lowerOne = ((WildcardType) two).getLowerBounds()[0];
        final Type lowerTwo = ((WildcardType) one).getLowerBounds()[0];
        equal = equal && lowerOne.equals(lowerTwo);

        // left type's bound must be lower: not a mistake! left (super inversion)!
        res = !equal && TypeUtils.isMoreSpecific(lowerOne, lowerTwo);
    }
    return res;
}
 
Example 7
Source File: ReflectionUtils.java    From spring-data-simpledb with MIT License 6 votes vote down vote up
private static boolean isSameConcreteType(Type firstType, Type secondType) {
	if(firstType instanceof ParameterizedType && secondType instanceof ParameterizedType) {

		Type firstRawType = ((ParameterizedType) firstType).getRawType();
		Class<?> firstTypeClass = (Class<?>) firstRawType;
		Type secondRawType = ((ParameterizedType) secondType).getRawType();
		Class<?> secondTypeClass = (Class<?>) secondRawType;

		if(firstTypeClass.isAssignableFrom(secondTypeClass)) {
			Type firstTypeArgument = ((ParameterizedType) firstType).getActualTypeArguments()[0];
			Type secondTypeArgument = ((ParameterizedType) secondType).getActualTypeArguments()[0];
			return isSameConcreteType(firstTypeArgument, secondTypeArgument);
		}
		return false;
	} else {
		return firstType.equals(secondType);
	}
}
 
Example 8
Source File: TransferablePropertyInvoker.java    From mango with Apache License 2.0 6 votes vote down vote up
private TransferablePropertyInvoker(PropertyMeta propertyMeta) {
  name = propertyMeta.getName();
  getter = propertyMeta.getReadMethod();
  setter = propertyMeta.getWriteMethod();
  actualPropertyToken = TypeToken.of(propertyMeta.getType());
  Transfer transAnno = propertyMeta.getPropertyAnno(Transfer.class);
  if (transAnno != null) {
    Class<? extends PropertyTransfer<?, ?>> transferClass = transAnno.value();
    propertyTransfer = Reflection.instantiateClass(transferClass);
    TokenTuple tokenTuple = TypeToken.of(transferClass).resolveFatherClassTuple(PropertyTransfer.class);
    TypeToken<?> columnToken = tokenTuple.getSecond();
    columnType = columnToken.getType();
    if (propertyTransfer.isCheckType()) {
      Type propertyType = tokenTuple.getFirst().getType();
      if (!propertyType.equals(actualPropertyToken.getType())) {
        throw new ClassCastException(String.format("error transfer<%s, %s> for property type %s",
            ToStringHelper.toString(propertyType), ToStringHelper.toString(columnType), ToStringHelper.toString(actualPropertyToken.getType())));
      }
    }
  } else {
    propertyTransfer = null;
    columnType = propertyMeta.getType();
  }
  handleMethod(getter);
  handleMethod(setter);
}
 
Example 9
Source File: ApiHandler.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
private String getType(Type classType, boolean firstParam) {
    if (classType.equals(String.class)) {
        return "string";
    }
    else if ((classType.equals(Integer.class)) ||
             (classType.equals(int.class))) {
        return "int";
    }
    else if (classType.equals(Date.class)) {
        return "date";
    }
    else if (classType.equals(Boolean.class) ||
             classType.equals(boolean.class)) {
        return "boolean";
    }
    else if (classType.equals(Map.class)) {
        return "struct";
    }
    else if ((classType.equals(List.class)) ||
             (classType.equals(Set.class)) ||
             (classType.toString().contains("class [L")) ||
             (classType.toString().contains("class [I"))) {
        return "array";
    }
    else if (classType.toString().contains("class [B")) {
        return "base64";
    }
    else if (classType.equals(com.redhat.rhn.domain.user.User.class) && firstParam) {
        // this is a workaround needed due to ef911709..2765f023bd
        return "string";
    }
    else {
        return "struct";
    }
}
 
Example 10
Source File: JAXBContextInitializer.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean shouldTypeBeAdded(final Type t2, final ParameterizedType parameterizedType) {
    if (!(t2 instanceof TypeVariable)) {
        return true;
    }
    TypeVariable<?> typeVariable = (TypeVariable<?>) t2;
    final Type[] bounds = typeVariable.getBounds();
    for (Type bound : bounds) {
        if (bound instanceof ParameterizedType && bound.equals(parameterizedType)) {
            return false;
        }
    }
    return true;
}
 
Example 11
Source File: JsonWrapperConverterFactory.java    From jus with Apache License 2.0 5 votes vote down vote up
@Override
public Converter<NetworkResponse, ?> fromResponse(Type type, Annotation[] annotations) {
    if (JsonElementWrapper.class.isAssignableFrom((Class<?>) type)) {
        if (type.equals(JsonObjectWrapper.class)) {
            return new JsonObjectWrapperResponseConverter();
        } else if (JsonObjectWrapper.class.isAssignableFrom((Class<?>) type)) {
            return new JsonObjectWrapperResponseConverter((Class<?>) type);
        } else if (type.equals(JsonStringArrayWrapper.class)) {
            return new JsonStringArrayWrapperResponseConverter();
        }

        if (type instanceof ParameterizedType) {
            Type type1 = ((ParameterizedType) type).getRawType();
            if (JsonObjectArrayWrapper.class.isAssignableFrom((Class<?>) type1)) {
                return new JsonObjectArrayWrapperResponseConverter
                        ((Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0]);
            }
        }

        if(defaultWrapperFactory!=null) {
            return new JsonWrapperResponseConverter(defaultWrapperFactory);
        }

        return null;
    }

    return null;
}
 
Example 12
Source File: FlinkNodeLoader.java    From sylph with Apache License 2.0 5 votes vote down vote up
private static void checkDataStreamRow(Class<?> pluginInterface, Class<?> driverClass)
{
    Type streamRow = JavaTypes.make(DataStream.class, new Type[] {Row.class}, null);
    Type checkType = JavaTypes.make(pluginInterface, new Type[] {streamRow}, null);

    for (Type type : driverClass.getGenericInterfaces()) {
        if (checkType.equals(type)) {
            return;
        }
    }
    throw new IllegalStateException(driverClass + " not is " + checkType + " ,your Generic is " + Arrays.asList(driverClass.getGenericInterfaces()));
}
 
Example 13
Source File: Lang_15_TypeUtils_s.java    From coming with MIT License 5 votes vote down vote up
private static Type unrollVariableAssignments(TypeVariable<?> var, Map<TypeVariable<?>, Type> typeVarAssigns) {
    Type result;
    do {
        result = typeVarAssigns.get(var);
        if (result instanceof TypeVariable<?> && !result.equals(var)) {
            var = (TypeVariable<?>) result;
            continue;
        }
        break;
    } while (true);
    return result;
}
 
Example 14
Source File: LocalApiProxyFactory.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 转换成ObjectMapper需要的JavaType类型
 */
private JavaType toJavaType(Type srcType, Type tarType,
                            Class<?> tarClass, Class<?> apiClazz) {
    if (tarType.equals(srcType)) {
        return null;
    }
    return JsonUtil.getMapper().constructType(
            PluginReflectUtil.parameterize(apiClazz, tarClass, tarType));
}
 
Example 15
Source File: GsonFieldConverterFactory.java    From friendspell with Apache License 2.0 5 votes vote down vote up
@Override
public FieldConverter<?> create(Cupboard cupboard, Type type) {
  if (type.equals(this.type)) {
    return new GsonFieldConverter(gson, type);
  }
  return null;
}
 
Example 16
Source File: TypeToken.java    From gson with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if two types are the same or are equivalent under a variable mapping
 * given in the type map that was provided.
 */
private static boolean matches(Type from, Type to, Map<String, Type> typeMap) {
  return to.equals(from)
      || (from instanceof TypeVariable
      && to.equals(typeMap.get(((TypeVariable<?>) from).getName())));

}
 
Example 17
Source File: UserProvider.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Override
public Injectable<UserGroupInformation> getInjectable(
    final ComponentContext componentContext, final Context context,
    final Type type) {
  return type.equals(UserGroupInformation.class)? this : null;
}
 
Example 18
Source File: IsFalse.java    From yare with MIT License 4 votes vote down vote up
private boolean isBoolean(Type type) {
    return type.equals(Boolean.class) || type.equals(boolean.class);
}
 
Example 19
Source File: Types.java    From feign with Apache License 2.0 4 votes vote down vote up
/**
 * Returns true if {@code a} and {@code b} are equal.
 */
static boolean equals(Type a, Type b) {
  if (a == b) {
    return true; // Also handles (a == null && b == null).

  } else if (a instanceof Class) {
    return a.equals(b); // Class already specifies equals().

  } else if (a instanceof ParameterizedType) {
    if (!(b instanceof ParameterizedType)) {
      return false;
    }
    ParameterizedType pa = (ParameterizedType) a;
    ParameterizedType pb = (ParameterizedType) b;
    return equal(pa.getOwnerType(), pb.getOwnerType())
        && pa.getRawType().equals(pb.getRawType())
        && Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments());

  } else if (a instanceof GenericArrayType) {
    if (!(b instanceof GenericArrayType)) {
      return false;
    }
    GenericArrayType ga = (GenericArrayType) a;
    GenericArrayType gb = (GenericArrayType) b;
    return equals(ga.getGenericComponentType(), gb.getGenericComponentType());

  } else if (a instanceof WildcardType) {
    if (!(b instanceof WildcardType)) {
      return false;
    }
    WildcardType wa = (WildcardType) a;
    WildcardType wb = (WildcardType) b;
    return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds())
        && Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());

  } else if (a instanceof TypeVariable) {
    if (!(b instanceof TypeVariable)) {
      return false;
    }
    TypeVariable<?> va = (TypeVariable<?>) a;
    TypeVariable<?> vb = (TypeVariable<?>) b;
    return va.getGenericDeclaration() == vb.getGenericDeclaration()
        && va.getName().equals(vb.getName());

  } else {
    return false; // This isn't a type we support!
  }
}
 
Example 20
Source File: ExplicitNullableTypeChecker.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Validates the given value for the given expected method parameter or
 * return value type.
 *
 * @param value
 *            the value to validate
 * @param expectedType
 *            the declared type expected for the value
 * @return error message when the value is null while the expected type does
 *         not explicitly allow null, or null meaning the value is OK.
 */
String checkValueForType(Object value, Type expectedType) {
    Class<?> clazz;
    if (expectedType instanceof TypeVariable){
        return null;
    } else if (expectedType instanceof ParameterizedType) {
        clazz = (Class<?>) ((ParameterizedType) expectedType).getRawType();
    } else {
        clazz = (Class<?>) expectedType;
    }

    if (value != null) {
        if (Iterable.class.isAssignableFrom(clazz)) {
            return checkIterable((Iterable) value, expectedType);
        } else if (clazz.isArray() && value instanceof Object[]) {
            return checkIterable(Arrays.asList((Object[]) value),
                    expectedType);
        } else if (Map.class.isAssignableFrom(clazz)) {
            return checkMapValues((Map<?, ?>) value, expectedType);
        } else if (expectedType instanceof Class<?>
                && !clazz.getName().startsWith("java.")) {
            return checkBeanFields(value, expectedType);
        } else {
            return null;
        }
    }

    if (expectedType.equals(Void.TYPE)) {
        // Corner case: void methods return null value by design
        return null;
    }

    if (Void.class.isAssignableFrom(clazz)) {
        // Corner case: explicit Void parameter
        return null;
    }

    if (Optional.class.isAssignableFrom(clazz)) {
        return String.format(
                "Got null value for type '%s', consider Optional.empty",
                expectedType.getTypeName());
    }

    return String.format(
            "Got null value for type '%s', which is neither Optional"
                    + " nor void",
            expectedType.getTypeName());
}