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

The following examples show how to use com.google.common.primitives.Primitives#unwrap() . 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: Reflection.java    From SkyblockAddons with MIT License 6 votes vote down vote up
/**
 * Gets a field with matching type.
 * <p>
 * The type is automatically checked against assignable types and primitives.
 * <p>
 * Super classes are automatically checked.
 *
 * @param type The type to look for.
 * @return The field with matching type.
 * @throws ReflectionException When the class or field cannot be located.
 */
public final FieldAccessor getField(Class<?> type) throws ReflectionException {
	Class<?> utype = (type.isPrimitive() ? Primitives.wrap(type) : Primitives.unwrap(type));

	if (FIELD_CACHE_CLASS.containsKey(this.getClazzPath())) {
		Map<Class<?>, FieldAccessor> fields = FIELD_CACHE_CLASS.get(this.getClazzPath());

		if (fields.containsKey(utype))
			return fields.get(utype);
	} else
		FIELD_CACHE_CLASS.put(this.getClazzPath(), new HashMap<>());

	for (Field field : this.getClazz().getDeclaredFields()) {
		if (field.getType().equals(type) || type.isAssignableFrom(field.getType()) || field.getType().equals(utype) || utype.isAssignableFrom(field.getType())) {
			field.setAccessible(true);
			FieldAccessor fieldAccessor = new FieldAccessor(this, field);
			FIELD_CACHE_CLASS.get(this.getClazzPath()).put(type, fieldAccessor);
			return fieldAccessor;
		}
	}

	if (this.getClazz().getSuperclass() != null)
		return this.getSuperReflection().getField(type);

	throw new ReflectionException(StringUtil.format("The field with type {0} was not found!", type));
}
 
Example 2
Source File: LiteralFunction.java    From presto with Apache License 2.0 6 votes vote down vote up
public static Type typeForMagicLiteral(Type type)
{
    Class<?> clazz = type.getJavaType();
    clazz = Primitives.unwrap(clazz);

    if (clazz == long.class) {
        return BIGINT;
    }
    if (clazz == double.class) {
        return DOUBLE;
    }
    if (!clazz.isPrimitive()) {
        if (type instanceof VarcharType) {
            return type;
        }
        else {
            return VARBINARY;
        }
    }
    if (clazz == boolean.class) {
        return BOOLEAN;
    }
    throw new IllegalArgumentException("Unhandled Java type: " + clazz.getName());
}
 
Example 3
Source File: JavaValue.java    From deobfuscator with Apache License 2.0 6 votes vote down vote up
public <T> T as(Class<T> clazz) {
	//TODO: Fix this
	if(value() instanceof JavaValue)
		return ((JavaValue)value()).as(clazz);
    if (Primitives.unwrap(clazz) != clazz) {
        throw new ExecutionException("Cannot call as(Class<T> clazz) with a primitive class");
    }
    if (value() instanceof Character && clazz == char.class) {
        return (T) value();
    }
    if (value() instanceof Integer && clazz == boolean.class) {
        return (T) Boolean.valueOf(intValue() != 0 ? true : false);
    }
    if (value() instanceof Byte && clazz == char.class) {
        return (T) Character.valueOf((char) ((JavaByte) this).byteValue());
    }
    return clazz.cast(value());
}
 
Example 4
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 5
Source File: Reflection.java    From SkyblockAddons with MIT License 5 votes vote down vote up
/**
 * Gets a method with matching return type and parameter types.
 * <p>
 * The return type and parameter types are automatically checked against assignable types and primitives.
 * <p>
 * Super classes are automatically checked.
 *
 * @param type The return type to look for.
 * @param paramTypes The types of parameters to look for.
 * @return The field with matching return type and parameter types.
 * @throws ReflectionException When the class or method cannot be located.
 */
public final MethodAccessor getMethod(Class<?> type, Class<?>... paramTypes) throws ReflectionException {
	Class<?> utype = (type.isPrimitive() ? Primitives.wrap(type) : Primitives.unwrap(type));
	Class<?>[] types = toPrimitiveTypeArray(paramTypes);

	if (METHOD_CACHE_CLASS.containsKey(this.getClazzPath())) {
		Map<Class<?>, Map<Class<?>[], MethodAccessor>> methods = METHOD_CACHE_CLASS.get(this.getClazzPath());

		if (methods.containsKey(type)) {
			Map<Class<?>[], MethodAccessor> returnTypeMethods = methods.get(type);

			for (Map.Entry<Class<?>[], MethodAccessor> entry : returnTypeMethods.entrySet()) {
				if (Arrays.equals(entry.getKey(), types)) {
					return entry.getValue();
				}
			}
		} else
			METHOD_CACHE_CLASS.get(this.getClazzPath()).put(type, new HashMap<>());
	} else {
		METHOD_CACHE_CLASS.put(this.getClazzPath(), new HashMap<>());
		METHOD_CACHE_CLASS.get(this.getClazzPath()).put(type, new HashMap<>());
	}

	for (Method method : this.getClazz().getDeclaredMethods()) {
		Class<?>[] methodTypes = toPrimitiveTypeArray(method.getParameterTypes());
		Class<?> returnType = method.getReturnType();

		if ((returnType.equals(type) || type.isAssignableFrom(returnType) || returnType.equals(utype) || utype.isAssignableFrom(returnType)) && isEqualsTypeArray(methodTypes, types)) {
			method.setAccessible(true);
			MethodAccessor methodAccessor = new MethodAccessor(this, method);
			METHOD_CACHE_CLASS.get(this.getClazzPath()).get(type).put(types, methodAccessor);
			return methodAccessor;
		}
	}

	if (this.getClazz().getSuperclass() != null)
		return this.getSuperReflection().getMethod(type, paramTypes);

	throw new ReflectionException(StringUtil.format("The method with return type {0} was not found with parameters {1}!", type, Arrays.asList(types)));
}
 
Example 6
Source File: Reflection.java    From SkyblockAddons with MIT License 5 votes vote down vote up
/**
 * Converts any primitive classes in the given classes to their primitive types.
 *
 * @param types The classes to convert.
 * @return Converted class types.
 */
public static Class<?>[] toPrimitiveTypeArray(Class<?>[] types) {
	Class<?>[] newTypes = new Class<?>[types != null ? types.length : 0];

	for (int i = 0; i < newTypes.length; i++)
		newTypes[i] = (types[i] != null ? Primitives.unwrap(types[i]) : null);

	return newTypes;
}
 
Example 7
Source File: Reflection.java    From SkyblockAddons with MIT License 5 votes vote down vote up
/**
 * Converts any primitive classes in the given objects to their primitive types.
 *
 * @param objects The objects to convert.
 * @return Converted class types.
 */
public static Class<?>[] toPrimitiveTypeArray(Object[] objects) {
	Class<?>[] newTypes = new Class<?>[objects != null ? objects.length : 0];

	for (int i = 0; i < newTypes.length; i++)
		newTypes[i] = (objects[i] != null ? Primitives.unwrap(objects[i].getClass()) : null);

	return newTypes;
}
 
Example 8
Source File: ParametricScalarImplementation.java    From presto with Apache License 2.0 5 votes vote down vote up
private void inferSpecialization(Method method, Class<?> parameterType, String typeParameterName)
{
    if (typeParameterNames.contains(typeParameterName) && parameterType != Object.class) {
        // Infer specialization on this type parameter.
        // We don't do this for Object because it could match any type.
        Class<?> specialization = specializedTypeParameters.get(typeParameterName);
        Class<?> nativeParameterType = Primitives.unwrap(parameterType);
        checkArgument(specialization == null || specialization.equals(nativeParameterType), "Method [%s] type %s has conflicting specializations %s and %s", method, typeParameterName, specialization, nativeParameterType);
        specializedTypeParameters.put(typeParameterName, nativeParameterType);
    }
}
 
Example 9
Source File: BytecodeUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
public static BytecodeBlock unboxPrimitiveIfNecessary(Scope scope, Class<?> boxedType)
{
    BytecodeBlock block = new BytecodeBlock();
    LabelNode end = new LabelNode("end");
    Class<?> unboxedType = Primitives.unwrap(boxedType);
    Variable wasNull = scope.getVariable("wasNull");

    if (unboxedType.isPrimitive()) {
        LabelNode notNull = new LabelNode("notNull");
        block.dup(boxedType)
                .ifNotNullGoto(notNull)
                .append(wasNull.set(constantTrue()))
                .comment("swap boxed null with unboxed default")
                .pop(boxedType)
                .pushJavaDefault(unboxedType)
                .gotoLabel(end)
                .visitLabel(notNull)
                .append(unboxPrimitive(unboxedType));
    }
    else {
        block.dup(boxedType)
                .ifNotNullGoto(end)
                .append(wasNull.set(constantTrue()));
    }
    block.visitLabel(end);

    return block;
}
 
Example 10
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 11
Source File: MethodAnalyzer.java    From deobfuscator with Apache License 2.0 5 votes vote down vote up
public StackObject(Class<?> type, Frame value, String desc) {
    if (Primitives.unwrap(type) != type) {
        throw new IllegalArgumentException();
    }
    this.type = type;
    this.value = value;
    this.initType = desc;
    if (type == Object.class && desc == null) {
        throw new IllegalArgumentException();
    }
}
 
Example 12
Source File: OpenTelemetrySpan.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Span setAttribute(String key, Number value) {
  Require.nonNull("Key", key);
  Require.nonNull("Value", value);

  Class<? extends Number> unwrapped = Primitives.unwrap(value.getClass());
  if (double.class.equals(unwrapped) || float.class.equals(unwrapped)) {
    span.setAttribute(key, value.doubleValue());
  } else {
    span.setAttribute(key, value.longValue());
  }

  return this;
}
 
Example 13
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);
}