예제 #1
1
    public ParameterEditDialog(Field field) {
      targetField = field;
      setBounds(20, 10, 100, 100);
      // Fieldの型を取得する
      Class<?> type = targetField.getType();
      if (type.isPrimitive()) {
        JSpinner valueSpnipper = new JSpinner();
        valueSpnipper.setPreferredSize(new Dimension(80, 20));
        GridBagLayoutUtil.setGbcLayout(
            0, 0, new GridBagConstraints(), valueSpnipper, new GridBagLayout(), this);
      }
      addKeyListener(
          new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {}

            @Override
            public void keyReleased(KeyEvent e) {}

            @Override
            public void keyPressed(KeyEvent e) {
              if (e.equals(KeyEvent.VK_ENTER)) {}
            }
          });
    }
    private void prepareLeftOperand(
        BooleanOperator operation,
        Class<?> type,
        Class<?> leftType,
        Class<?> rightType,
        Label shortcutEvaluation) {
      if (leftType.isPrimitive()) {
        if (type != null) {
          castOrCoercePrimitive(LEFT_OPERAND, leftType, type);
        }
        return;
      }

      Label notNullLabel =
          jitLeftIsNull(
              type == null || leftType == type
                  ? jitNullSafeOperationStart()
                  : jitNullSafeCoercion(leftType, type));

      if (operation.isEquality() && !rightType.isPrimitive()) {
        // if (left == null) return right == null
        checkNullEquality();
      } else {
        // if (left == null) return false
        mv.visitInsn(ICONST_0);
      }

      mv.visitJumpInsn(GOTO, shortcutEvaluation);
      mv.visitLabel(notNullLabel);
    }
예제 #3
0
 public static Object convertArrayElements(Class<?> arrayType, Object array) {
   Class<?> src = array.getClass().getComponentType();
   Class<?> dst = arrayType.getComponentType();
   if (src == null || dst == null) throw new IllegalArgumentException("not array type");
   Wrapper sw = (src.isPrimitive() ? Wrapper.forPrimitiveType(src) : null);
   Wrapper dw = (dst.isPrimitive() ? Wrapper.forPrimitiveType(dst) : null);
   int length;
   if (sw == null) {
     Object[] a = (Object[]) array;
     length = a.length;
     if (dw == null) return Arrays.copyOf(a, length, arrayType.asSubclass(Object[].class));
     Object res = dw.makeArray(length);
     dw.copyArrayUnboxing(a, 0, res, 0, length);
     return res;
   }
   length = j86.java.lang.reflect.Array.getLength(array);
   Object[] res;
   if (dw == null) {
     res = Arrays.copyOf(NO_ARGS_ARRAY, length, arrayType.asSubclass(Object[].class));
   } else {
     res = new Object[length];
   }
   sw.copyArrayBoxing(array, 0, res, 0, length);
   if (dw == null) return res;
   Object a = dw.makeArray(length);
   dw.copyArrayUnboxing(res, 0, a, 0, length);
   return a;
 }
예제 #4
0
 /**
  * Returns whether first type is assignable from second one or not.
  *
  * @param type checked whether is assignable, always not null
  * @param from checked type, might be null
  * @return true if first type is assignable from second one, false otherwise
  */
 public static boolean isAssignable(final Class type, final Class from) {
   if (from == null) {
     return !type.isPrimitive();
   } else if (type.isAssignableFrom(from)) {
     return true;
   } else if (type.isPrimitive()) {
     if (type == boolean.class) {
       return Boolean.class.isAssignableFrom(from);
     } else if (type == int.class) {
       return Integer.class.isAssignableFrom(from);
     } else if (type == char.class) {
       return Character.class.isAssignableFrom(from);
     } else if (type == byte.class) {
       return Byte.class.isAssignableFrom(from);
     } else if (type == short.class) {
       return Short.class.isAssignableFrom(from);
     } else if (type == long.class) {
       return Long.class.isAssignableFrom(from);
     } else if (type == float.class) {
       return Float.class.isAssignableFrom(from);
     } else if (type == double.class) {
       return Double.class.isAssignableFrom(from);
     } else if (type == void.class) {
       return Void.class.isAssignableFrom(from);
     }
   }
   return false;
 }
예제 #5
0
파일: TypeUtils.java 프로젝트: mfwzan/astor
  /**
   * @param cls
   * @param toClass
   * @param subtypeVarAssigns
   * @return
   */
  private static Map<TypeVariable<?>, Type> getTypeArguments(
      Class<?> cls, Class<?> toClass, Map<TypeVariable<?>, Type> subtypeVarAssigns) {
    // make sure they're assignable
    if (!isAssignable(cls, toClass)) {
      return null;
    }

    // can't work with primitives
    if (cls.isPrimitive()) {
      // both classes are primitives?
      if (toClass.isPrimitive()) {
        // dealing with widening here. No type arguments to be
        // harvested with these two types.
        return new HashMap<TypeVariable<?>, Type>();
      }

      // work with wrapper the wrapper class instead of the primitive
      cls = ClassUtils.primitiveToWrapper(cls);
    }

    // create a copy of the incoming map, or an empty one if it's null
    HashMap<TypeVariable<?>, Type> typeVarAssigns =
        subtypeVarAssigns == null
            ? new HashMap<TypeVariable<?>, Type>()
            : new HashMap<TypeVariable<?>, Type>(subtypeVarAssigns);

    // no arguments for the parameters, or target class has been reached
    if (cls.getTypeParameters().length > 0 || toClass.equals(cls)) {
      return typeVarAssigns;
    }

    // walk the inheritance hierarchy until the target class is reached
    return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
  }
예제 #6
0
 /**
  * @param parameterTypes
  * @param parameters
  * @return true when the signature fits
  */
 private static boolean signatureFits(Class[] parameterTypes, Object[] parameters) {
   if ((parameterTypes == null && parameters != null)
       || (parameterTypes != null && parameters == null)
       || (parameterTypes.length != parameters.length)) {
     return false;
   }
   for (int i = 0; i < parameters.length; i++) {
     Object parameter = parameters[i];
     Class parameterType = parameterTypes[i];
     if (parameter == null) {
       if (parameterType.isPrimitive()) {
         return false;
       }
       continue; // null fits any class
     }
     Class parameterClass = parameter.getClass();
     if (!(parameterType.isAssignableFrom(parameterClass)
         || (parameterType.isPrimitive() && isCompatible(parameterType, parameterClass)))) {
       //				System.out.println("- signature-mismatch: wanted=" + parameterType + ", have=" +
       // parameter.getClass() );
       return false;
       //			} else {
       //				System.out.println("+ signature-match: wanted=" + parameterType + ", have=" +
       // parameter.getClass() );
     }
   }
   return true;
 }
 private static MethodHandle getOptimisticTypeGuard(
     final Class<?> actual, final Class<?> provable) {
   final MethodHandle guard;
   final int provableTypeIndex = getProvableTypeIndex(provable);
   if (actual == int.class) {
     guard = ENSURE_INT[provableTypeIndex];
   } else if (actual == double.class) {
     guard = ENSURE_NUMBER[provableTypeIndex];
   } else {
     guard = null;
     assert !actual.isPrimitive() : actual + ", " + provable;
   }
   if (guard != null && !(provable.isPrimitive())) {
     // Make sure filtering a MethodHandle(...)String works with a filter MethodHandle(Object,
     // int)... Note that
     // if the return type of the method is incompatible with Number, then the guard will always
     // throw an
     // UnwarrantedOperationException when invoked, but we must link it anyway as we need the
     // guarded function to
     // successfully execute and return the non-convertible return value that it'll put into the
     // thrown
     // UnwarrantedOptimismException.
     return guard.asType(guard.type().changeParameterType(0, provable));
   }
   return guard;
 }
예제 #8
0
  /** Creates a {@link PluginPropertyField} based on the given field. */
  private PluginPropertyField createPluginProperty(Field field, TypeToken<?> resolvingType)
      throws UnsupportedTypeException {
    TypeToken<?> fieldType = resolvingType.resolveType(field.getGenericType());
    Class<?> rawType = fieldType.getRawType();

    Name nameAnnotation = field.getAnnotation(Name.class);
    Description descAnnotation = field.getAnnotation(Description.class);
    String name = nameAnnotation == null ? field.getName() : nameAnnotation.value();
    String description = descAnnotation == null ? "" : descAnnotation.value();

    if (rawType.isPrimitive()) {
      return new PluginPropertyField(name, description, rawType.getName(), true);
    }

    rawType = Primitives.unwrap(rawType);
    if (!rawType.isPrimitive() && !String.class.equals(rawType)) {
      throw new UnsupportedTypeException("Only primitive and String types are supported");
    }

    boolean required = true;
    for (Annotation annotation : field.getAnnotations()) {
      if (annotation.annotationType().getName().endsWith(".Nullable")) {
        required = false;
        break;
      }
    }

    return new PluginPropertyField(
        name, description, rawType.getSimpleName().toLowerCase(), required);
  }
  private static boolean isClassAssignable(Class<?> supertype, Class<?> type) {
    // Class.isAssignableFrom does not perform primitive widening
    if (supertype.isPrimitive() && type.isPrimitive()) {
      return SUBTYPES_BY_PRIMITIVE.get(supertype).contains(type);
    }

    return supertype.isAssignableFrom(type);
  }
예제 #10
0
 static boolean isAssignable(@NonNull Class<?> expected, @NonNull Class<?> actual) {
   if (expected.isAssignableFrom(actual)) {
     return true;
   }
   if (expected.isPrimitive()) {
     return Dynamic.unbox(expected).isAssignableFrom(actual);
   }
   return actual.isPrimitive() && expected.isAssignableFrom(Dynamic.unbox(actual));
 }
예제 #11
0
 /**
  * Checks if one <code>Class</code> can be assigned to a variable of another <code>Class</code>.
  *
  * <p>Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this method takes into
  * account widenings of primitive classes and <code>null</code>s.
  *
  * <p>Primitive widenings allow an int to be assigned to a long, float or double. This method
  * returns the correct result for these cases.
  *
  * <p><code>Null</code> may be assigned to any reference type. This method will return <code>true
  * </code> if <code>null</code> is passed in and the toClass is non-primitive.
  *
  * <p>Specifically, this method tests whether the type represented by the specified <code>Class
  * </code> parameter can be converted to the type represented by this <code>Class</code> object
  * via an identity conversion widening primitive or widening reference conversion. See <em><a
  * href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>, sections
  * 5.1.1, 5.1.2 and 5.1.4 for details.
  *
  * @param cls the Class to check, may be null
  * @param toClass the Class to try to assign into, returns false if null
  * @return <code>true</code> if assignment possible
  */
 public static boolean isAssignable(Class cls, Class toClass) {
   if (toClass == null) {
     return false;
   }
   // have to check for null, as isAssignableFrom doesn't
   if (cls == null) {
     return !(toClass.isPrimitive());
   }
   if (cls.equals(toClass)) {
     return true;
   }
   if (cls.isPrimitive()) {
     if (toClass.isPrimitive() == false) {
       return false;
     }
     if (Integer.TYPE.equals(cls)) {
       return Long.TYPE.equals(toClass)
           || Float.TYPE.equals(toClass)
           || Double.TYPE.equals(toClass);
     }
     if (Long.TYPE.equals(cls)) {
       return Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
     }
     if (Boolean.TYPE.equals(cls)) {
       return false;
     }
     if (Double.TYPE.equals(cls)) {
       return false;
     }
     if (Float.TYPE.equals(cls)) {
       return Double.TYPE.equals(toClass);
     }
     if (Character.TYPE.equals(cls)) {
       return Integer.TYPE.equals(toClass)
           || Long.TYPE.equals(toClass)
           || Float.TYPE.equals(toClass)
           || Double.TYPE.equals(toClass);
     }
     if (Short.TYPE.equals(cls)) {
       return Integer.TYPE.equals(toClass)
           || Long.TYPE.equals(toClass)
           || Float.TYPE.equals(toClass)
           || Double.TYPE.equals(toClass);
     }
     if (Byte.TYPE.equals(cls)) {
       return Short.TYPE.equals(toClass)
           || Integer.TYPE.equals(toClass)
           || Long.TYPE.equals(toClass)
           || Float.TYPE.equals(toClass)
           || Double.TYPE.equals(toClass);
     }
     // should never get here
     return false;
   }
   return toClass.isAssignableFrom(cls);
 }
예제 #12
0
 /** Creates a class identifier of form Labc/abc;, from a Class. */
 public static String ci(Class n) {
   if (n.isArray()) {
     n = n.getComponentType();
     if (n.isPrimitive()) {
       if (n == Byte.TYPE) {
         return "[B";
       } else if (n == Boolean.TYPE) {
         return "[Z";
       } else if (n == Short.TYPE) {
         return "[S";
       } else if (n == Character.TYPE) {
         return "[C";
       } else if (n == Integer.TYPE) {
         return "[I";
       } else if (n == Float.TYPE) {
         return "[F";
       } else if (n == Double.TYPE) {
         return "[D";
       } else if (n == Long.TYPE) {
         return "[J";
       } else {
         throw new RuntimeException("Unrecognized type in compiler: " + n.getName());
       }
     } else {
       return "[" + ci(n);
     }
   } else {
     if (n.isPrimitive()) {
       if (n == Byte.TYPE) {
         return "B";
       } else if (n == Boolean.TYPE) {
         return "Z";
       } else if (n == Short.TYPE) {
         return "S";
       } else if (n == Character.TYPE) {
         return "C";
       } else if (n == Integer.TYPE) {
         return "I";
       } else if (n == Float.TYPE) {
         return "F";
       } else if (n == Double.TYPE) {
         return "D";
       } else if (n == Long.TYPE) {
         return "J";
       } else if (n == Void.TYPE) {
         return "V";
       } else {
         throw new RuntimeException("Unrecognized type in compiler: " + n.getName());
       }
     } else {
       return "L" + p(n) + ";";
     }
   }
 }
예제 #13
0
파일: Mirror.java 프로젝트: jekey/nutz
 /**
  * @param type 目标类型
  * @return 判断当前对象是否能直接转换到目标类型,而不产生异常
  */
 public boolean canCastToDirectly(Class<?> type) {
   if (klass == type || type.isAssignableFrom(klass)) return true;
   if (klass.isPrimitive() && type.isPrimitive()) {
     if (this.isPrimitiveNumber() && Mirror.me(type).isPrimitiveNumber()) return true;
   }
   try {
     return Mirror.me(type).getWrapperClass() == this.getWrapperClass();
   } catch (Exception e) {
   }
   return false;
 }
예제 #14
0
  @SuppressWarnings("unchecked")
  @Override
  public Function<Object[], ?> visit(UnaryExpression e) {
    final Function<Object[], ?> first = e.getFirst().accept(this);
    switch (e.getExpressionType()) {
      case ExpressionType.ArrayLength:
        return t -> Array.getLength(first.apply(t));
      case ExpressionType.BitwiseNot:
        return (Function<Object[], ?>) bitwiseNot((Function<Object[], Number>) first);
      case ExpressionType.Convert:
        final Class<?> to = e.getResultType();
        if (to.isPrimitive() || Number.class.isAssignableFrom(to))
          return t -> {
            Object source = first.apply(t);
            if (source instanceof Number) {
              Number result = (Number) source;
              if (to.isPrimitive()) {
                if (to == Integer.TYPE) return result.intValue();
                if (to == Long.TYPE) return result.longValue();
                if (to == Float.TYPE) return result.floatValue();
                if (to == Double.TYPE) return result.doubleValue();
                if (to == Byte.TYPE) return result.byteValue();
                if (to == Character.TYPE) return (char) result.intValue();
                if (to == Short.TYPE) return result.shortValue();
              } else if (result != null) {
                if (to == BigInteger.class) return BigInteger.valueOf(result.longValue());
                if (to == BigDecimal.class) return BigDecimal.valueOf(result.doubleValue());
              }
            }
            if (source instanceof Character) {
              if (to == Integer.TYPE) return (int) (char) source;
              if (to == Long.TYPE) return (long) (char) source;
              if (to == Float.TYPE) return (float) (char) source;
              if (to == Double.TYPE) return (double) (char) source;
            }
            return to.cast(source);
          };

        return first;
      case ExpressionType.IsNull:
        return first.andThen(r -> r == null);
      case ExpressionType.LogicalNot:
        return normalize(not((Function<Object[], Boolean>) first));
      case ExpressionType.Negate:
        return (Function<Object[], ?>) negate((Function<Object[], Number>) first);
      case ExpressionType.Quote:
        return constant(first);
        // case ExpressionType.UnaryPlus:
        // return abs((Function<? extends Number, Object[]>) first);
      default:
        throw new IllegalArgumentException(ExpressionType.toString(e.getExpressionType()));
    }
  }
  /**
   * Define an operation on the managed object. Defines an operation with parameters. Refection is
   * used to determine find the method and it's return type. The description of the method is found
   * with a call to findDescription on "name(signature)". The name and description of each parameter
   * is found with a call to findDescription with "name(partialSignature", the returned description
   * is for the last parameter of the partial signature and is assumed to start with the parameter
   * name, followed by a colon.
   *
   * @param name The name of the method call.
   * @param signature The types of the operation parameters.
   * @param impact Impact as defined in MBeanOperationInfo
   * @param onMBean true if the operation is defined on the mbean
   */
  public synchronized void defineOperation(
      String name, String[] signature, int impact, boolean onMBean) {
    _dirty = true;
    Class oClass = onMBean ? this.getClass() : _object.getClass();
    if (signature == null) signature = new String[0];

    try {
      Class[] types = new Class[signature.length];
      MBeanParameterInfo[] pInfo = new MBeanParameterInfo[signature.length];

      // Check types and build methodKey
      String methodKey = name + "(";
      for (int i = 0; i < signature.length; i++) {
        Class type = TypeUtil.fromName(signature[i]);
        if (type == null)
          type = Thread.currentThread().getContextClassLoader().loadClass(signature[i]);
        types[i] = type;
        signature[i] = type.isPrimitive() ? TypeUtil.toName(type) : signature[i];
        methodKey += (i > 0 ? "," : "") + signature[i];
      }
      methodKey += ")";

      // Build param infos
      for (int i = 0; i < signature.length; i++) {
        String description = findDescription(methodKey + "[" + i + "]");
        int colon = description.indexOf(":");
        if (colon < 0) {
          description = "param" + i + ":" + description;
          colon = description.indexOf(":");
        }
        pInfo[i] =
            new MBeanParameterInfo(
                description.substring(0, colon).trim(),
                signature[i],
                description.substring(colon + 1).trim());
      }

      // build the operation info
      Method method = oClass.getMethod(name, types);
      Class returnClass = method.getReturnType();
      _method.put(methodKey, method);
      _operations.add(
          new ModelMBeanOperationInfo(
              name,
              findDescription(methodKey),
              pInfo,
              returnClass.isPrimitive() ? TypeUtil.toName(returnClass) : (returnClass.getName()),
              impact));
    } catch (Exception e) {
      log.warn("operation " + name, e);
      throw new IllegalArgumentException(e.toString());
    }
  }
예제 #16
0
 public Object newInstance(Object... args)
     throws InstantiationException, IllegalAccessException, IllegalArgumentException,
         InvocationTargetException {
   if (args.length == 0) {
     return clazz.newInstance();
   }
   Constructor<?> bestCt = null;
   Constructor<?>[] cts = clazz.getConstructors();
   ctsLoop:
   for (Constructor<?> ct : cts) {
     Class<?>[] pts = ct.getParameterTypes();
     if (pts.length != args.length) {
       continue;
     }
     boolean perfectMatch = true;
     for (int k = 0; k < pts.length; k++) {
       Class<?> pt = pts[k];
       Object arg = args[k];
       if (arg == null) {
         if (pt.isPrimitive()) {
           continue ctsLoop; // never match
         } else {
           continue; // always match
         }
       }
       Class<?> at = arg.getClass();
       if (at == pt) {
         continue;
       }
       if (pt.isPrimitive()) {
         if (PRIMITIVES_TO_WRAPPERS.get(pt) == at) {
           continue;
         } else {
           continue ctsLoop;
         }
       }
       perfectMatch = false;
       if (!pt.isAssignableFrom(at)) {
         continue ctsLoop;
       }
     }
     bestCt = ct;
     if (perfectMatch) {
       break;
     }
   }
   if (bestCt == null) {
     throw new InstantiationException();
   }
   Object res = bestCt.newInstance(args);
   return res;
 }
  // the overload of type Object for Groovy coercions:  public void setFoo(Object foo)
  private void createTypeConvertingSetter(
      ClassVisitor visitor, Type generatedType, ModelProperty<?> property) {
    if (!property.isWritable() || !(property.getSchema() instanceof ScalarValueSchema)) {
      return;
    }

    Class<?> propertyClass = property.getType().getConcreteClass();
    Type propertyType = Type.getType(propertyClass);
    Class<?> boxedClass =
        propertyClass.isPrimitive() ? BOXED_TYPES.get(propertyClass) : propertyClass;
    Type boxedType = Type.getType(boxedClass);

    Method setter = property.getSetter().getMethod();
    MethodVisitor methodVisitor =
        declareMethod(
            visitor,
            setter.getName(),
            SET_OBJECT_PROPERTY_DESCRIPTOR,
            SET_OBJECT_PROPERTY_DESCRIPTOR);

    putThisOnStack(methodVisitor);
    putTypeConverterFieldValueOnStack(methodVisitor, generatedType);

    // Object converted = $typeConverter.convert(foo, Float.class, false);
    methodVisitor.visitVarInsn(ALOAD, 1); // put var #1 ('foo') on the stack
    methodVisitor.visitLdcInsn(boxedType); // push the constant Class onto the stack
    methodVisitor.visitInsn(
        propertyClass.isPrimitive()
            ? ICONST_1
            : ICONST_0); // push int 1 or 0 (interpreted as true or false) onto the stack
    methodVisitor.visitMethodInsn(
        INVOKEINTERFACE,
        TYPE_CONVERTER_TYPE.getInternalName(),
        "convert",
        COERCE_TO_SCALAR_DESCRIPTOR,
        true);
    methodVisitor.visitTypeInsn(CHECKCAST, boxedType.getInternalName());

    if (propertyClass.isPrimitive()) {
      unboxType(methodVisitor, propertyClass);
    }

    // invoke the typed setter, popping 'this' and 'converted' from the stack
    methodVisitor.visitMethodInsn(
        INVOKEVIRTUAL,
        generatedType.getInternalName(),
        setter.getName(),
        Type.getMethodDescriptor(Type.VOID_TYPE, propertyType),
        false);
    finishVisitingMethod(methodVisitor);
  }
예제 #18
0
    @Override
    public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
      // try {
      String key = m.getName();

      if (args.length == 0) {
        // built-in
        if ("objectData".equals(key)) return new ParseObjectData(obj);
        if (ParseBase.PARSE_OBJECT.equals(key)) return obj;

        // user define
        final Class<?> returnType = m.getReturnType();
        String typeName = returnType.getName();
        if (typeName.equalsIgnoreCase("float")) {
          return (float) obj.getDouble(key);
        } else {
          Object object = obj.get(key);
          if (returnType.isPrimitive() && object == null) {
            return 0;
          } else if (object != null
              && ParseObject.class.isInstance(object)
              && ParseBase.class.isAssignableFrom(returnType)) {
            return ((ParseFacade<?>) ParseFacade.get(returnType)).wrap((ParseObject) object);
          } else if (object != null
              && !returnType.isInstance(object)
              && !returnType.isPrimitive()) {
            return null;
          } else {
            return object;
          }
        }
      } else { // arg.length == 1
        // set value
        Object object = args[0];
        if (key.equals("objectId")) System.out.println("value " + object);

        if (object instanceof ParseBase) {
          obj.put(key, ((ParseBase) object).parseObject());
        } else {
          obj.put(key, object);
        }

        return null;
      }
      // } catch (InvocationTargetException e) {
      // throw e.getTargetException();
      // } catch (Exception e) {
      // throw e;
      // }
      // return something
    }
예제 #19
0
 /*non-public*/
 static boolean canConvert(Class<?> src, Class<?> dst) {
   // short-circuit a few cases:
   if (src == dst || dst == Object.class) return true;
   // the remainder of this logic is documented in MethodHandle.asType
   if (src.isPrimitive()) {
     // can force void to an explicit null, a la reflect.Method.invoke
     // can also force void to a primitive zero, by analogy
     if (src == void.class) return true; // or !dst.isPrimitive()?
     Wrapper sw = Wrapper.forPrimitiveType(src);
     if (dst.isPrimitive()) {
       // P->P must widen
       return Wrapper.forPrimitiveType(dst).isConvertibleFrom(sw);
     } else {
       // P->R must box and widen
       return dst.isAssignableFrom(sw.wrapperType());
     }
   } else if (dst.isPrimitive()) {
     // any value can be dropped
     if (dst == void.class) return true;
     Wrapper dw = Wrapper.forPrimitiveType(dst);
     // R->P must be able to unbox (from a dynamically chosen type) and widen
     // For example:
     //   Byte/Number/Comparable/Object -> dw:Byte -> byte.
     //   Character/Comparable/Object -> dw:Character -> char
     //   Boolean/Comparable/Object -> dw:Boolean -> boolean
     // This means that dw must be cast-compatible with src.
     if (src.isAssignableFrom(dw.wrapperType())) {
       return true;
     }
     // The above does not work if the source reference is strongly typed
     // to a wrapper whose primitive must be widened.  For example:
     //   Byte -> unbox:byte -> short/int/long/float/double
     //   Character -> unbox:char -> int/long/float/double
     if (Wrapper.isWrapperType(src) && dw.isConvertibleFrom(Wrapper.forWrapperType(src))) {
       // can unbox from src and then widen to dst
       return true;
     }
     // We have already covered cases which arise due to runtime unboxing
     // of a reference type which covers several wrapper types:
     //   Object -> cast:Integer -> unbox:int -> long/float/double
     //   Serializable -> cast:Byte -> unbox:byte -> byte/short/int/long/float/double
     // An marginal case is Number -> dw:Character -> char, which would be OK if there were a
     // subclass of Number which wraps a value that can convert to char.
     // Since there is none, we don't need an extra check here to cover char or boolean.
     return false;
   } else {
     // R->R always works, since null is always valid dynamically
     return true;
   }
 }
 public void add(
     Class definedIn,
     String fieldName,
     String itemFieldName,
     Class itemType,
     String keyFieldName) {
   Field field = null;
   Class declaredIn = definedIn;
   while (declaredIn != Object.class) {
     try {
       field = declaredIn.getDeclaredField(fieldName);
       break;
     } catch (SecurityException e) {
       throw new InitializationException("Access denied for field with implicit collection", e);
     } catch (NoSuchFieldException e) {
       declaredIn = declaredIn.getSuperclass();
     }
   }
   if (field == null) {
     throw new InitializationException("No field \"" + fieldName + "\" for implicit collection");
   } else if (Map.class.isAssignableFrom(field.getType())) {
     if (itemFieldName == null && keyFieldName == null) {
       itemType = Map.Entry.class;
     }
   } else if (!Collection.class.isAssignableFrom(field.getType())) {
     Class fieldType = field.getType();
     if (!fieldType.isArray()) {
       throw new InitializationException(
           "Field \"" + fieldName + "\" declares no collection or array");
     } else {
       Class componentType = fieldType.getComponentType();
       componentType = componentType.isPrimitive() ? Primitives.box(componentType) : componentType;
       if (itemType == null) {
         itemType = componentType;
       } else {
         itemType = itemType.isPrimitive() ? Primitives.box(itemType) : itemType;
         if (!componentType.isAssignableFrom(itemType)) {
           throw new InitializationException(
               "Field \""
                   + fieldName
                   + "\" declares an array, but the array type is not compatible with "
                   + itemType.getName());
         }
       }
     }
   }
   ImplicitCollectionMapperForClass mapper = getOrCreateMapper(definedIn);
   mapper.add(new ImplicitCollectionMappingImpl(fieldName, itemType, itemFieldName, keyFieldName));
 }
 @Override
 public MethodHandle getElementSetter(final Class<?> elementType) {
   return elementType.isPrimitive()
       ? getContinuousElementSetter(
           MH.asType(SET_ELEM, SET_ELEM.type().changeParameterType(2, elementType)), elementType)
       : null;
 }
 @SuppressWarnings("unchecked")
 public static JsonSerializer<Object> getStdKeySerializer(JavaType keyType) {
   if (keyType == null) {
     return DEFAULT_KEY_SERIALIZER;
   }
   Class<?> cls = keyType.getRawClass();
   if (cls == String.class) {
     return DEFAULT_STRING_SERIALIZER;
   }
   if (cls == Object.class || cls.isPrimitive() || Number.class.isAssignableFrom(cls)) {
     return DEFAULT_KEY_SERIALIZER;
   }
   if (Date.class.isAssignableFrom(cls)) {
     return (JsonSerializer<Object>) DateKeySerializer.instance;
   }
   if (Calendar.class.isAssignableFrom(cls)) {
     return (JsonSerializer<Object>) CalendarKeySerializer.instance;
   }
   /* 14-Mar-2014, tatu: Should support @JsonValue, as per #47; but that
    *   requires extensive introspection, and passing in more information
    *   to this method.
    */
   // If no match, just use default one:
   return DEFAULT_KEY_SERIALIZER;
 }
 @Override
 public int getMemory(Object obj) {
   if (!isArray(obj)) {
     return super.getMemory(obj);
   }
   int size = 64;
   Class<?> type = obj.getClass().getComponentType();
   if (type.isPrimitive()) {
     int len = Array.getLength(obj);
     if (type == boolean.class) {
       size += len;
     } else if (type == byte.class) {
       size += len;
     } else if (type == char.class) {
       size += len * 2;
     } else if (type == short.class) {
       size += len * 2;
     } else if (type == int.class) {
       size += len * 4;
     } else if (type == float.class) {
       size += len * 4;
     } else if (type == double.class) {
       size += len * 8;
     } else if (type == long.class) {
       size += len * 8;
     }
   } else {
     for (Object x : (Object[]) obj) {
       if (x != null) {
         size += elementType.getMemory(x);
       }
     }
   }
   return size;
 }
 // This converts a class type to it's AST node representation
 private static Type fromClass(Class<?> _class) {
   final String name = _class.getSimpleName();
   if (_class.isPrimitive()) {
     return new PrimitiveType(Primitive.valueOf(capitalize(name)));
   }
   return new ClassOrInterfaceType(name);
 }
예제 #25
0
  /**
   * Return the value of a simple property with the specified name.
   *
   * @param name Name of the property whose value is to be retrieved
   * @return The property's value
   * @exception IllegalArgumentException if there is no property of the specified name
   */
  public Object get(final String name) {

    // Return any non-null value for the specified property
    final Object value = values.get(name);
    if (value != null) {
      return (value);
    }

    // Return a null value for a non-primitive property
    final Class<?> type = getDynaProperty(name).getType();
    if (!type.isPrimitive()) {
      return (value);
    }

    // Manufacture default values for primitive properties
    if (type == Boolean.TYPE) {
      return (Boolean.FALSE);
    } else if (type == Byte.TYPE) {
      return (new Byte((byte) 0));
    } else if (type == Character.TYPE) {
      return (new Character((char) 0));
    } else if (type == Double.TYPE) {
      return (new Double(0.0));
    } else if (type == Float.TYPE) {
      return (new Float((float) 0.0));
    } else if (type == Integer.TYPE) {
      return (new Integer(0));
    } else if (type == Long.TYPE) {
      return (new Long(0));
    } else if (type == Short.TYPE) {
      return (new Short((short) 0));
    } else {
      return (null);
    }
  }
 private Object[] createNullArguments(Class[] parameterTypes) {
   Object[] arguments = new Object[parameterTypes.length];
   for (int i = 0; i < arguments.length; i++) {
     Class type = parameterTypes[i];
     if (type.isPrimitive()) {
       if (type == byte.class) {
         arguments[i] = new Byte((byte) 0);
       } else if (type == short.class) {
         arguments[i] = new Short((short) 0);
       } else if (type == int.class) {
         arguments[i] = new Integer(0);
       } else if (type == long.class) {
         arguments[i] = new Long(0);
       } else if (type == float.class) {
         arguments[i] = new Float(0);
       } else if (type == double.class) {
         arguments[i] = new Double(0);
       } else if (type == char.class) {
         arguments[i] = new Character('\0');
       } else {
         arguments[i] = Boolean.FALSE;
       }
     }
   }
   return arguments;
 }
예제 #27
0
 /**
  * Clone an object.
  *
  * @param o the object to clone
  * @return the clone if the object implements {@link Cloneable} otherwise <code>null</code>
  * @throws CloneFailedException if the object is cloneable and the clone operation fails
  * @since 2.6
  */
 public static Object clone(final Object o) {
   if (o instanceof Cloneable) {
     final Object result;
     if (o.getClass().isArray()) {
       final Class componentType = o.getClass().getComponentType();
       if (!componentType.isPrimitive()) {
         result = ((Object[]) o).clone();
       } else {
         int length = Array.getLength(o);
         result = Array.newInstance(componentType, length);
         while (length-- > 0) {
           Array.set(result, length, Array.get(o, length));
         }
       }
     } else {
       try {
         result = MethodUtils.invokeMethod(o, "clone", null);
       } catch (final NoSuchMethodException e) {
         throw new CloneFailedException(
             "Cloneable type " + o.getClass().getName() + " has no clone method", e);
       } catch (final IllegalAccessException e) {
         throw new CloneFailedException(
             "Cannot clone Cloneable type " + o.getClass().getName(), e);
       } catch (final InvocationTargetException e) {
         throw new CloneFailedException(
             "Exception cloning Cloneable type " + o.getClass().getName(), e.getTargetException());
       }
     }
     return result;
   }
   return null;
 }
예제 #28
0
 /** @return if the class represents an array of immutable values. */
 private boolean isArrayOfImmutableTypes(Class<?> clazz) {
   if (!clazz.isArray()) {
     return false;
   }
   Class<?> component = clazz.getComponentType();
   return component.isPrimitive() || isImmutable(component);
 }
예제 #29
0
 private Type getType(Class cls) {
   Type type = null;
   if (cls.isPrimitive() || Number.class.isAssignableFrom(cls)) {
     type = Type.PRIMITIVE;
   } else if (Character.class.isAssignableFrom(cls)) {
     type = Type.CHAR;
   } else if (String.class.isAssignableFrom(cls)) {
     type = Type.STRING;
   } else if (Date.class.isAssignableFrom(cls)) {
     type = Type.DATE;
   } else if (Calendar.class.isAssignableFrom(cls)) {
     type = Type.CALENDAR;
   } else if (BigInteger.class.isAssignableFrom(cls)) {
     type = Type.BIG_INTEGER;
   } else if (BigDecimal.class.isAssignableFrom(cls)) {
     type = Type.BIG_DECIMAL;
   } else if (cls.isArray()) {
     type = Type.ARRAY;
   } else if (Map.class.isAssignableFrom(cls)) {
     type = Type.MAP;
   } else if (Collection.class.isAssignableFrom(cls)) {
     type = Type.COLLECTION;
   } else {
     type = Type.OBJECT;
   }
   return type;
 }
 private Object sample(Class<?> type) {
   if (type.isPrimitive()) {
     if (type == long.class) {
       return random.nextLong();
     }
     if (type == boolean.class) {
       return random.nextBoolean();
     }
   } else if (type.isEnum()) {
     Object[] candidates = type.getEnumConstants();
     return candidates[random.nextInt(candidates.length)];
   } else if (!type.isArray()) {
     if (type == String.class) {
       StringBuilder result = new StringBuilder();
       for (int len = 5 + random.nextInt(10); len > 0; len--) {
         result.append('a' + random.nextInt('z' - 'a'));
       }
       return result.toString();
     }
     if (type == Long.class) {
       return random.nextLong();
     }
     return mock(type);
   }
   throw new UnsupportedOperationException(
       "doesn't support " + type + " please add support for it.");
 }