-
CSR
-
Resolution: Approved
-
P4
-
None
-
source
-
minimal
-
Add new static method to a final class.
-
Java API
-
SE
Summary
Add the method Class.forPrimitiveName(String)
to map from the name of a primitive type (int
, long
, etc.) to a Class
object.
Problem
A long-standing gap in built-in core reflection functionality was a direct mapping from the name of a primitive type to its corresponding class object. At least one implementation of this functionality appears privately in the JDK.
Solution
Add a Class.forPrimitiveName(String)
that maps "int"
to int.class
, "long"
to long.class
, etc.
Specification
--- a/src/java.base/share/classes/java/lang/Class.java
+++ b/src/java.base/share/classes/java/lang/Class.java
@@ -438,6 +438,8 @@ public final class Class<T> implements java.io.Serializable,
* If {@code name} denotes a primitive type or void, for example {@code I},
* an attempt will be made to locate a user-defined class in the unnamed package
* whose name is {@code I} instead.
+ * To obtain a {@code Class} object for a named primitive type + * such as {@code int} or {@code long} use {@link + * #forPrimitiveName(String)}. * *
To obtain the {@code Class} object associated with an array class, * the name consists of one or more {@code '['} representing the depth @@ -628,6 +630,41 @@ public final class Class implements java.io.Serializable, } }
+ /**
+ * {@return the {@code Class} object associated with the
+ * {@linkplain #isPrimitive() primitive type} of the given name}
+ * If the argument is not the name of a primitive type, {@code
+ * null} is returned.
+ *
+ * @param primitiveName the name of the primitive type to find
+ *
+ * @throws NullPointerException if the argument is {@code null}
+ *
+ * @jls 4.2 Primitive Types and Values
+ * @jls 15.8.2 Class Literals
+ * @since 22
+ */
+ public static Class<?> forPrimitiveName(String primitiveName) {
+ return switch(primitiveName) {
+ // Integral types
+ case "int" -> int.class;
+ case "long" -> long.class;
+ case "short" -> short.class;
+ case "char" -> char.class;
+ case "byte" -> byte.class;
+
+ // Floating-point types
+ case "float" -> float.class;
+ case "double" -> double.class;
+
+ // Other types
+ case "boolean" -> boolean.class;
+ case "void" -> void.class;
+
+ default -> null;
+ };
+ }
+
/**
* Creates a new instance of the class represented by this {@code Class}
* object. The class is instantiated as if by a {@code new}
- csr of
-
JDK-6361826 (reflect) provide method for mapping strings to class object for primitive types
-
- Resolved
-