< prev index next >

src/java.base/share/classes/java/lang/runtime/ObjectMethods.java

Print this page

 51 public class ObjectMethods {
 52 
 53     private ObjectMethods() { }
 54 
 55     private static final MethodType DESCRIPTOR_MT = MethodType.methodType(MethodType.class);
 56     private static final MethodType NAMES_MT = MethodType.methodType(List.class);
 57     private static final MethodHandle FALSE = MethodHandles.constant(boolean.class, false);
 58     private static final MethodHandle TRUE = MethodHandles.constant(boolean.class, true);
 59     private static final MethodHandle ZERO = MethodHandles.constant(int.class, 0);
 60     private static final MethodHandle CLASS_IS_INSTANCE;
 61     private static final MethodHandle OBJECT_EQUALS;
 62     private static final MethodHandle OBJECTS_EQUALS;
 63     private static final MethodHandle OBJECTS_HASHCODE;
 64     private static final MethodHandle OBJECTS_TOSTRING;
 65     private static final MethodHandle OBJECT_EQ;
 66     private static final MethodHandle OBJECT_HASHCODE;
 67     private static final MethodHandle OBJECT_TO_STRING;
 68     private static final MethodHandle STRING_FORMAT;
 69     private static final MethodHandle HASH_COMBINER;
 70 
 71     private static final HashMap<Class<?>, MethodHandle> primitiveEquals = new HashMap<>();


 72     private static final HashMap<Class<?>, MethodHandle> primitiveHashers = new HashMap<>();
 73     private static final HashMap<Class<?>, MethodHandle> primitiveToString = new HashMap<>();
 74 
 75     static {
 76         try {
 77             Class<ObjectMethods> OBJECT_METHODS_CLASS = ObjectMethods.class;
 78             MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
 79             MethodHandles.Lookup lookup = MethodHandles.lookup();
 80 
 81             @SuppressWarnings("removal")
 82             ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
 83                 @Override public ClassLoader run() { return ClassLoader.getPlatformClassLoader(); }
 84             });
 85 
 86             CLASS_IS_INSTANCE = publicLookup.findVirtual(Class.class, "isInstance",
 87                                                          MethodType.methodType(boolean.class, Object.class));
 88             OBJECT_EQUALS = publicLookup.findVirtual(Object.class, "equals",
 89                                                      MethodType.methodType(boolean.class, Object.class));
 90             OBJECT_HASHCODE = publicLookup.findVirtual(Object.class, "hashCode",
 91                                                        MethodType.fromMethodDescriptorString("()I", loader));

230      * @return the method handle
231      */
232     private static MethodHandle makeHashCode(Class<?> receiverClass,
233                                             List<MethodHandle> getters) {
234         MethodHandle accumulator = MethodHandles.dropArguments(ZERO, 0, receiverClass); // (R)I
235 
236         // @@@ Use loop combinator instead?
237         for (MethodHandle getter : getters) {
238             MethodHandle hasher = hasher(getter.type().returnType()); // (T)I
239             MethodHandle hashThisField = MethodHandles.filterArguments(hasher, 0, getter);    // (R)I
240             MethodHandle combineHashes = MethodHandles.filterArguments(HASH_COMBINER, 0, accumulator, hashThisField); // (RR)I
241             accumulator = MethodHandles.permuteArguments(combineHashes, accumulator.type(), 0, 0); // adapt (R)I to (RR)I
242         }
243 
244         return accumulator;
245     }
246 
247     /**
248      * Generates a method handle for the {@code toString} method for a given data class
249      * @param receiverClass   the data class

250      * @param getters         the list of getters
251      * @param names           the names
252      * @return the method handle
253      */
254     private static MethodHandle makeToString(Class<?> receiverClass,
255                                             List<MethodHandle> getters,
256                                             List<String> names) {

257         // This is a pretty lousy algorithm; we spread the receiver over N places,
258         // apply the N getters, apply N toString operations, and concat the result with String.format
259         // Better to use String.format directly, or delegate to StringConcatFactory
260         // Also probably want some quoting around String components
261 
262         assert getters.size() == names.size();
263 
264         int[] invArgs = new int[getters.size()];
265         Arrays.fill(invArgs, 0);
266         MethodHandle[] filters = new MethodHandle[getters.size()];
267         StringBuilder sb = new StringBuilder();
268         sb.append(receiverClass.getSimpleName()).append("[");
269         for (int i=0; i<getters.size(); i++) {
270             MethodHandle getter = getters.get(i); // (R)T
271             MethodHandle stringify = stringifier(getter.type().returnType()); // (T)String
272             MethodHandle stringifyThisField = MethodHandles.filterArguments(stringify, 0, getter);    // (R)String
273             filters[i] = stringifyThisField;
274             sb.append(names.get(i)).append("=%s");
275             if (i != getters.size() - 1)
276                 sb.append(", ");
277         }
278         sb.append(']');
279         String formatString = sb.toString();
280         MethodHandle formatter = MethodHandles.insertArguments(STRING_FORMAT, 0, formatString)
281                                               .asCollector(String[].class, getters.size()); // (R*)String
282         if (getters.size() == 0) {
283             // Add back extra R
284             formatter = MethodHandles.dropArguments(formatter, 0, receiverClass);
285         }
286         else {
287             MethodHandle filtered = MethodHandles.filterArguments(formatter, 0, filters);
288             formatter = MethodHandles.permuteArguments(filtered, MethodType.methodType(String.class, receiverClass), invArgs);

325      * @return             a call site if invoked by indy, or a method handle
326      *                     if invoked by a condy
327      * @throws IllegalArgumentException if the bootstrap arguments are invalid
328      *                                  or inconsistent
329      * @throws NullPointerException if any argument but {@code lookup} is {@code null},
330      *                              in the case of the {@code getters} argument, its
331      *                              contents cannot be {@code null} either
332      * @throws Throwable if any exception is thrown during call site construction
333      */
334     public static Object bootstrap(MethodHandles.Lookup lookup, String methodName, TypeDescriptor type,
335                                    Class<?> recordClass,
336                                    String names,
337                                    MethodHandle... getters) throws Throwable {
338         requireNonNull(methodName);
339         requireNonNull(type);
340         requireNonNull(recordClass);
341         requireNonNull(names);
342         requireNonNull(getters);
343         Arrays.stream(getters).forEach(Objects::requireNonNull);
344         MethodType methodType;
345         if (type instanceof MethodType mt)

346             methodType = mt;
347         else {



348             methodType = null;
349             if (!MethodHandle.class.equals(type))
350                 throw new IllegalArgumentException(type.toString());
351         }
352         List<MethodHandle> getterList = List.of(getters);





353         MethodHandle handle = switch (methodName) {
354             case "equals"   -> {
355                 if (methodType != null && !methodType.equals(MethodType.methodType(boolean.class, recordClass, Object.class)))
356                     throw new IllegalArgumentException("Bad method type: " + methodType);
357                 yield makeEquals(recordClass, getterList);
358             }
359             case "hashCode" -> {
360                 if (methodType != null && !methodType.equals(MethodType.methodType(int.class, recordClass)))
361                     throw new IllegalArgumentException("Bad method type: " + methodType);
362                 yield makeHashCode(recordClass, getterList);
363             }
364             case "toString" -> {
365                 if (methodType != null && !methodType.equals(MethodType.methodType(String.class, recordClass)))
366                     throw new IllegalArgumentException("Bad method type: " + methodType);
367                 List<String> nameList = "".equals(names) ? List.of() : List.of(names.split(";"));
368                 if (nameList.size() != getterList.size())
369                     throw new IllegalArgumentException("Name list and accessor list do not match");
370                 yield makeToString(recordClass, getterList, nameList);
371             }
372             default -> throw new IllegalArgumentException(methodName);
373         };
374         return methodType != null ? new ConstantCallSite(handle) : handle;
375     }
376 }

 51 public class ObjectMethods {
 52 
 53     private ObjectMethods() { }
 54 
 55     private static final MethodType DESCRIPTOR_MT = MethodType.methodType(MethodType.class);
 56     private static final MethodType NAMES_MT = MethodType.methodType(List.class);
 57     private static final MethodHandle FALSE = MethodHandles.constant(boolean.class, false);
 58     private static final MethodHandle TRUE = MethodHandles.constant(boolean.class, true);
 59     private static final MethodHandle ZERO = MethodHandles.constant(int.class, 0);
 60     private static final MethodHandle CLASS_IS_INSTANCE;
 61     private static final MethodHandle OBJECT_EQUALS;
 62     private static final MethodHandle OBJECTS_EQUALS;
 63     private static final MethodHandle OBJECTS_HASHCODE;
 64     private static final MethodHandle OBJECTS_TOSTRING;
 65     private static final MethodHandle OBJECT_EQ;
 66     private static final MethodHandle OBJECT_HASHCODE;
 67     private static final MethodHandle OBJECT_TO_STRING;
 68     private static final MethodHandle STRING_FORMAT;
 69     private static final MethodHandle HASH_COMBINER;
 70 
 71     /* package-private */
 72     static final HashMap<Class<?>, MethodHandle> primitiveEquals = new HashMap<>();
 73 
 74     private static final HashMap<Class<?>, MethodHandle> primitiveHashers = new HashMap<>();
 75     private static final HashMap<Class<?>, MethodHandle> primitiveToString = new HashMap<>();
 76 
 77     static {
 78         try {
 79             Class<ObjectMethods> OBJECT_METHODS_CLASS = ObjectMethods.class;
 80             MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
 81             MethodHandles.Lookup lookup = MethodHandles.lookup();
 82 
 83             @SuppressWarnings("removal")
 84             ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
 85                 @Override public ClassLoader run() { return ClassLoader.getPlatformClassLoader(); }
 86             });
 87 
 88             CLASS_IS_INSTANCE = publicLookup.findVirtual(Class.class, "isInstance",
 89                                                          MethodType.methodType(boolean.class, Object.class));
 90             OBJECT_EQUALS = publicLookup.findVirtual(Object.class, "equals",
 91                                                      MethodType.methodType(boolean.class, Object.class));
 92             OBJECT_HASHCODE = publicLookup.findVirtual(Object.class, "hashCode",
 93                                                        MethodType.fromMethodDescriptorString("()I", loader));

232      * @return the method handle
233      */
234     private static MethodHandle makeHashCode(Class<?> receiverClass,
235                                             List<MethodHandle> getters) {
236         MethodHandle accumulator = MethodHandles.dropArguments(ZERO, 0, receiverClass); // (R)I
237 
238         // @@@ Use loop combinator instead?
239         for (MethodHandle getter : getters) {
240             MethodHandle hasher = hasher(getter.type().returnType()); // (T)I
241             MethodHandle hashThisField = MethodHandles.filterArguments(hasher, 0, getter);    // (R)I
242             MethodHandle combineHashes = MethodHandles.filterArguments(HASH_COMBINER, 0, accumulator, hashThisField); // (RR)I
243             accumulator = MethodHandles.permuteArguments(combineHashes, accumulator.type(), 0, 0); // adapt (R)I to (RR)I
244         }
245 
246         return accumulator;
247     }
248 
249     /**
250      * Generates a method handle for the {@code toString} method for a given data class
251      * @param receiverClass   the data class
252      * @param simpleName      the simple name of the record class
253      * @param getters         the list of getters
254      * @param names           the names
255      * @return the method handle
256      */
257     private static MethodHandle makeToString(Class<?> receiverClass,
258                                              String simpleName,
259                                              List<MethodHandle> getters,
260                                              List<String> names) {
261         // This is a pretty lousy algorithm; we spread the receiver over N places,
262         // apply the N getters, apply N toString operations, and concat the result with String.format
263         // Better to use String.format directly, or delegate to StringConcatFactory
264         // Also probably want some quoting around String components
265 
266         assert getters.size() == names.size();
267 
268         int[] invArgs = new int[getters.size()];
269         Arrays.fill(invArgs, 0);
270         MethodHandle[] filters = new MethodHandle[getters.size()];
271         StringBuilder sb = new StringBuilder();
272         sb.append(simpleName).append("[");
273         for (int i=0; i<getters.size(); i++) {
274             MethodHandle getter = getters.get(i); // (R)T
275             MethodHandle stringify = stringifier(getter.type().returnType()); // (T)String
276             MethodHandle stringifyThisField = MethodHandles.filterArguments(stringify, 0, getter);    // (R)String
277             filters[i] = stringifyThisField;
278             sb.append(names.get(i)).append("=%s");
279             if (i != getters.size() - 1)
280                 sb.append(", ");
281         }
282         sb.append(']');
283         String formatString = sb.toString();
284         MethodHandle formatter = MethodHandles.insertArguments(STRING_FORMAT, 0, formatString)
285                                               .asCollector(String[].class, getters.size()); // (R*)String
286         if (getters.size() == 0) {
287             // Add back extra R
288             formatter = MethodHandles.dropArguments(formatter, 0, receiverClass);
289         }
290         else {
291             MethodHandle filtered = MethodHandles.filterArguments(formatter, 0, filters);
292             formatter = MethodHandles.permuteArguments(filtered, MethodType.methodType(String.class, receiverClass), invArgs);

329      * @return             a call site if invoked by indy, or a method handle
330      *                     if invoked by a condy
331      * @throws IllegalArgumentException if the bootstrap arguments are invalid
332      *                                  or inconsistent
333      * @throws NullPointerException if any argument but {@code lookup} is {@code null},
334      *                              in the case of the {@code getters} argument, its
335      *                              contents cannot be {@code null} either
336      * @throws Throwable if any exception is thrown during call site construction
337      */
338     public static Object bootstrap(MethodHandles.Lookup lookup, String methodName, TypeDescriptor type,
339                                    Class<?> recordClass,
340                                    String names,
341                                    MethodHandle... getters) throws Throwable {
342         requireNonNull(methodName);
343         requireNonNull(type);
344         requireNonNull(recordClass);
345         requireNonNull(names);
346         requireNonNull(getters);
347         Arrays.stream(getters).forEach(Objects::requireNonNull);
348         MethodType methodType;
349         Class<?> receiverType = recordClass.isPrimitiveClass() ? recordClass.asValueType() : recordClass;
350         if (type instanceof MethodType mt) {
351             methodType = mt;
352             if (mt.parameterType(0) != receiverType) {
353                 throw new IllegalArgumentException("Bad method type: " + mt);
354             }
355         } else {
356             methodType = null;
357             if (!MethodHandle.class.equals(type))
358                 throw new IllegalArgumentException(type.toString());
359         }
360         List<MethodHandle> getterList = List.of(getters);
361         for (MethodHandle getter : getterList) {
362             if (getter.type().parameterType(0) != receiverType) {
363                 throw new IllegalArgumentException("Bad receiver type: " + getter);
364             }
365         }
366         MethodHandle handle = switch (methodName) {
367             case "equals"   -> {
368                 if (methodType != null && !methodType.equals(MethodType.methodType(boolean.class, receiverType, Object.class)))
369                     throw new IllegalArgumentException("Bad method type: " + methodType);
370                 yield makeEquals(receiverType, getterList);
371             }
372             case "hashCode" -> {
373                 if (methodType != null && !methodType.equals(MethodType.methodType(int.class, receiverType)))
374                     throw new IllegalArgumentException("Bad method type: " + methodType);
375                 yield makeHashCode(receiverType, getterList);
376             }
377             case "toString" -> {
378                 if (methodType != null && !methodType.equals(MethodType.methodType(String.class, receiverType)))
379                     throw new IllegalArgumentException("Bad method type: " + methodType);
380                 List<String> nameList = "".equals(names) ? List.of() : List.of(names.split(";"));
381                 if (nameList.size() != getterList.size())
382                     throw new IllegalArgumentException("Name list and accessor list do not match");
383                 yield makeToString(receiverType, recordClass.getSimpleName(), getterList, nameList);
384             }
385             default -> throw new IllegalArgumentException(methodName);
386         };
387         return methodType != null ? new ConstantCallSite(handle) : handle;
388     }
389 }
< prev index next >