Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8190982

primitive type conversion utility methods to java.lang.Class or java.util.Objects



    • Type: Enhancement
    • Status: Open
    • Priority: P3
    • Resolution: Unresolved
    • Affects Version/s: None
    • Fix Version/s: None
    • Component/s: core-libs
    • Labels:


      Sometimes when working with wrapper types we wish to emulate the conversions performed by Core Reflection or MethodHandles.asType or the Java language itself (for assignment and method call). These conversions are the same as Class::cast, except when either type is a primitive, in which case boxing, unboxing, or widening primitive conversions may occur. Usually the source value is already wrapped in an object, and the target type (if not a wrapper) is a primitive type, which may require re-boxing in a widened primitive format.

      This API point could be placed on Class as Class::convert, or else as a static method Objects::convertToType.

      Recently, this API point has been needed for coding up logic that relates to CONSTANT_Dynamic bootstrap methods. The programmer often reaches for Class::cast to convert the result, but this is wrong for primitive types, and the corner case may be discovered quite late. For such usage, it would be best if the API point were Class::convert, so that it can be discovered easily.

      A second possible API point would be a query on Class to ask, if it is a primitive type, what is its corresponding wrapper type. Today this can be obtained by the expression `MethodType.methodType(cls).wrap().returnType()`, but that idiom is difficult to discover.

      A third possible API point would be a casting conversion, which would also allow other conversions, such as narrowing primitive conversions. This could be added as Objects::casToType or Class::castValue. This API point should probably be aligned with MethodHandles.explicitCastArguments, which throws in additional "forced move" casts in addition to primitive narrowing.

      See comments for sample code.




            Unassigned Unassigned
            jrose John Rose
            0 Vote for this issue
            4 Start watching this issue