8225054: Compiler implementation for records

8225052: javax.lang.model support for records
8225053: Preview APIs support for records
8225055: Javadoc for records
8226314: com.sun.source support for records
8227113: Specification for java.lang.Record
8233526: JVM support for records

Implement records in the compiler and the JVM, including serialization, reflection and APIs support

Co-authored-by: Brian Goetz <brian.goetz@oracle.com>
Co-authored-by: Maurizio Cimadamore <maurizio.cimadamore@oracle.com>
Co-authored-by: Harold Seigel <harold.seigel@oracle.com>
Co-authored-by: Joe Darcy <joe.darcy@oracle.com>
Co-authored-by: Jonathan Gibbons <jonathan.gibbons@oracle.com>
Co-authored-by: Chris Hegarty <chris.hegarty@oracle.com>
Co-authored-by: Jan Lahoda <jan.lahoda@oracle.com>
Reviewed-by: mcimadamore, briangoetz, alanb, darcy, chegar, jrose, jlahoda, coleenp, dholmes, lfoltan, mchung, sadayapalam, hannesw, sspitsyn
This commit is contained in:
Vicente Romero 2019-12-04 15:57:39 -05:00
parent 0a375cfa2d
commit 827e5e3226
351 changed files with 24958 additions and 6395 deletions

View file

@ -26,7 +26,9 @@
package java.io;
import java.io.ObjectStreamClass.WeakClassKey;
import java.io.ObjectStreamClass.RecordSupport;
import java.lang.System.Logger;
import java.lang.invoke.MethodHandle;
import java.lang.ref.ReferenceQueue;
import java.lang.reflect.Array;
import java.lang.reflect.Modifier;
@ -218,6 +220,39 @@ import sun.reflect.misc.ReflectUtil;
* Similarly, any serialPersistentFields or serialVersionUID field declarations
* are also ignored--all enum types have a fixed serialVersionUID of 0L.
*
* @implSpec
* <a id="record-serialization"></a>
* Records are serialized differently than ordinary serializable or externalizable
* objects. The serialized form of a record object is a sequence of values derived
* from the record components. The stream format of a record object is the same as
* that of an ordinary object in the stream. During deserialization, if the local
* class equivalent of the specified stream class descriptor is a record class,
* then first the stream fields are read and reconstructed to serve as the record's
* component values; and second, a record object is created by invoking the
* record's <i>canonical</i> constructor with the component values as arguments (or the
* default value for component's type if a component value is absent from the
* stream).
* Like other serializable or externalizable objects, record objects can function
* as the target of back references appearing subsequently in the serialization
* stream. However, a cycle in the graph where the record object is referred to,
* either directly or transitively, by one of its components, is not preserved.
* The record components are deserialized prior to the invocation of the record
* constructor, hence this limitation (see
* <a href="{@docRoot}/../specs/serialization/serial-arch.html#cyclic-references">
* [Section 1.14, "Circular References"</a> for additional information).
* The process by which record objects are serialized or externalized cannot be
* customized; any class-specific writeObject, readObject, readObjectNoData,
* writeExternal, and readExternal methods defined by record classes are
* ignored during serialization and deserialization. However, a substitute object
* to be serialized or a designate replacement may be specified, by the
* writeReplace and readResolve methods, respectively. Any
* serialPersistentFields field declaration is ignored. Documenting serializable
* fields and data for record classes is unnecessary, since there is no variation
* in the serial form, other than whether a substitute or replacement object is
* used. The serialVersionUID of a record class is 0L unless explicitly
* declared. The requirement for matching serialVersionUID values is waived for
* record classes.
*
* @author Mike Warres
* @author Roger Riggs
* @see java.io.DataInput
@ -2047,6 +2082,11 @@ public class ObjectInputStream
return result;
}
@SuppressWarnings("preview")
private static boolean isRecord(Class<?> cls) {
return cls.isRecord();
}
/**
* Reads and returns "ordinary" (i.e., not a String, Class,
* ObjectStreamClass, array, or enum constant) object, or null if object's
@ -2085,7 +2125,12 @@ public class ObjectInputStream
handles.markException(passHandle, resolveEx);
}
if (desc.isExternalizable()) {
final boolean isRecord = cl != null && isRecord(cl) ? true : false;
if (isRecord) {
assert obj == null;
obj = readRecord(desc);
handles.setObject(passHandle, obj);
} else if (desc.isExternalizable()) {
readExternalData((Externalizable) obj, desc);
} else {
readSerialData(obj, desc);
@ -2171,6 +2216,43 @@ public class ObjectInputStream
*/
}
/** Reads a record. */
private Object readRecord(ObjectStreamClass desc) throws IOException {
ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
if (slots.length != 1) {
// skip any superclass stream field values
for (int i = 0; i < slots.length-1; i++) {
ObjectStreamClass slotDesc = slots[i].desc;
if (slots[i].hasData) {
defaultReadFields(null, slotDesc);
}
}
}
FieldValues fieldValues = defaultReadFields(null, desc);
// retrieve the canonical constructor
MethodHandle ctrMH = desc.getRecordConstructor();
// bind the stream field values
ctrMH = RecordSupport.bindCtrValues(ctrMH, desc, fieldValues);
try {
return ctrMH.invoke();
} catch (Exception e) {
InvalidObjectException ioe = new InvalidObjectException(e.getMessage());
ioe.initCause(e);
throw ioe;
} catch (Error e) {
throw e;
} catch (Throwable t) {
ObjectStreamException ose = new InvalidObjectException(
"ReflectiveOperationException during deserialization");
ose.initCause(t);
throw ose;
}
}
/**
* Reads (or attempts to skip, if obj is null or is tagged with a
* ClassNotFoundException) instance data for each serializable class of
@ -2317,7 +2399,7 @@ public class ObjectInputStream
}
}
private class FieldValues {
/*package-private*/ class FieldValues {
final byte[] primValues;
final Object[] objValues;

View file

@ -150,6 +150,10 @@ import sun.reflect.misc.ReflectUtil;
* defaultWriteObject and writeFields initially terminate any existing
* block-data record.
*
* @implSpec
* Records are serialized differently than ordinary serializable or externalizable
* objects, see <a href="ObjectInputStream.html#record-serialization">record serialization</a>.
*
* @author Mike Warres
* @author Roger Riggs
* @see java.io.DataOutput
@ -1431,7 +1435,10 @@ public class ObjectOutputStream
bout.writeByte(TC_OBJECT);
writeClassDesc(desc, false);
handles.assign(unshared ? null : obj);
if (desc.isExternalizable() && !desc.isProxy()) {
if (desc.isRecord()) {
writeRecordData(obj, desc);
} else if (desc.isExternalizable() && !desc.isProxy()) {
writeExternalData((Externalizable) obj);
} else {
writeSerialData(obj, desc);
@ -1475,6 +1482,21 @@ public class ObjectOutputStream
curPut = oldPut;
}
/** Writes the record component values for the given record object. */
@SuppressWarnings("preview")
private void writeRecordData(Object obj, ObjectStreamClass desc)
throws IOException
{
assert obj.getClass().isRecord();
ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
if (slots.length != 1) {
throw new InvalidClassException(
"expected a single record slot length, but found: " + slots.length);
}
defaultWriteFields(obj, desc); // #### seems unnecessary to use the accessors
}
/**
* Writes instance data for each serializable class of given object, from
* superclass to subclass.

View file

@ -25,6 +25,8 @@
package java.io;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
@ -32,6 +34,7 @@ import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.RecordComponent;
import java.lang.reflect.UndeclaredThrowableException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
@ -44,6 +47,8 @@ import java.security.NoSuchAlgorithmException;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
@ -123,6 +128,8 @@ public class ObjectStreamClass implements Serializable {
private boolean isProxy;
/** true if represents enum type */
private boolean isEnum;
/** true if represents record type */
private boolean isRecord;
/** true if represented class implements Serializable */
private boolean serializable;
/** true if represented class implements Externalizable */
@ -184,6 +191,8 @@ public class ObjectStreamClass implements Serializable {
/** serialization-appropriate constructor, or null if none */
private Constructor<?> cons;
/** record canonical constructor, or null */
private MethodHandle canonicalCtr;
/** protection domains that need to be checked when calling the constructor */
private ProtectionDomain[] domains;
@ -261,6 +270,9 @@ public class ObjectStreamClass implements Serializable {
public long getSerialVersionUID() {
// REMIND: synchronize instead of relying on volatile?
if (suid == null) {
if (isRecord)
return 0L;
suid = AccessController.doPrivileged(
new PrivilegedAction<Long>() {
public Long run() {
@ -467,6 +479,11 @@ public class ObjectStreamClass implements Serializable {
}
}
@SuppressWarnings("preview")
private static boolean isRecord(Class<?> cls) {
return cls.isRecord();
}
/**
* Creates local class descriptor representing given class.
*/
@ -475,6 +492,7 @@ public class ObjectStreamClass implements Serializable {
name = cl.getName();
isProxy = Proxy.isProxyClass(cl);
isEnum = Enum.class.isAssignableFrom(cl);
isRecord = isRecord(cl);
serializable = Serializable.class.isAssignableFrom(cl);
externalizable = Externalizable.class.isAssignableFrom(cl);
@ -505,7 +523,9 @@ public class ObjectStreamClass implements Serializable {
fields = NO_FIELDS;
}
if (externalizable) {
if (isRecord) {
canonicalCtr = canonicalRecordCtr(cl);
} else if (externalizable) {
cons = getExternalizableConstructor(cl);
} else {
cons = getSerializableConstructor(cl);
@ -542,14 +562,18 @@ public class ObjectStreamClass implements Serializable {
if (deserializeEx == null) {
if (isEnum) {
deserializeEx = new ExceptionInfo(name, "enum type");
} else if (cons == null) {
} else if (cons == null && !isRecord) {
deserializeEx = new ExceptionInfo(name, "no valid constructor");
}
}
for (int i = 0; i < fields.length; i++) {
if (fields[i].getField() == null) {
defaultSerializeEx = new ExceptionInfo(
name, "unmatched serializable field(s) declared");
if (isRecord && canonicalCtr == null) {
deserializeEx = new ExceptionInfo(name, "record canonical constructor not found");
} else {
for (int i = 0; i < fields.length; i++) {
if (fields[i].getField() == null) {
defaultSerializeEx = new ExceptionInfo(
name, "unmatched serializable field(s) declared");
}
}
}
initialized = true;
@ -682,7 +706,7 @@ public class ObjectStreamClass implements Serializable {
}
if (model.serializable == osc.serializable &&
!cl.isArray() &&
!cl.isArray() && !isRecord(cl) &&
suid != osc.getSerialVersionUID()) {
throw new InvalidClassException(osc.name,
"local class incompatible: " +
@ -714,6 +738,10 @@ public class ObjectStreamClass implements Serializable {
}
this.cl = cl;
if (cl != null) {
this.isRecord = isRecord(cl);
this.canonicalCtr = osc.canonicalCtr;
}
this.resolveEx = resolveEx;
this.superDesc = superDesc;
name = model.name;
@ -739,12 +767,14 @@ public class ObjectStreamClass implements Serializable {
deserializeEx = localDesc.deserializeEx;
}
domains = localDesc.domains;
assert isRecord(cl) ? localDesc.cons == null : true;
cons = localDesc.cons;
}
fieldRefl = getReflector(fields, localDesc);
// reassign to matched fields so as to reflect local unshared settings
fields = fieldRefl.getFields();
initialized = true;
}
@ -966,6 +996,15 @@ public class ObjectStreamClass implements Serializable {
return isEnum;
}
/**
* Returns true if class descriptor represents a record type, false
* otherwise.
*/
boolean isRecord() {
requireInitialized();
return isRecord;
}
/**
* Returns true if represented class implements Externalizable, false
* otherwise.
@ -1518,6 +1557,37 @@ public class ObjectStreamClass implements Serializable {
return reflFactory.newConstructorForSerialization(cl);
}
/**
* Returns the canonical constructor for the given record class, or null if
* the not found ( which should never happen for correctly generated record
* classes ).
*/
@SuppressWarnings("preview")
private static MethodHandle canonicalRecordCtr(Class<?> cls) {
assert isRecord(cls) : "Expected record, got: " + cls;
PrivilegedAction<MethodHandle> pa = () -> {
Class<?>[] paramTypes = Arrays.stream(cls.getRecordComponents())
.map(RecordComponent::getType)
.toArray(Class<?>[]::new);
try {
Constructor<?> ctr = cls.getConstructor(paramTypes);
ctr.setAccessible(true);
return MethodHandles.lookup().unreflectConstructor(ctr);
} catch (IllegalAccessException | NoSuchMethodException e) {
return null;
}
};
return AccessController.doPrivileged(pa);
}
/**
* Returns the canonical constructor, if the local class equivalent of this
* stream class descriptor is a record class, otherwise null.
*/
MethodHandle getRecordConstructor() {
return canonicalCtr;
}
/**
* Returns non-static, non-abstract method with given signature provided it
* is defined by or accessible (via inheritance) by the given class, or
@ -1641,12 +1711,16 @@ public class ObjectStreamClass implements Serializable {
private static ObjectStreamField[] getSerialFields(Class<?> cl)
throws InvalidClassException
{
if (!Serializable.class.isAssignableFrom(cl))
return NO_FIELDS;
ObjectStreamField[] fields;
if (Serializable.class.isAssignableFrom(cl) &&
!Externalizable.class.isAssignableFrom(cl) &&
if (isRecord(cl)) {
fields = getDefaultSerialFields(cl);
Arrays.sort(fields);
} else if (!Externalizable.class.isAssignableFrom(cl) &&
!Proxy.isProxyClass(cl) &&
!cl.isInterface())
{
!cl.isInterface()) {
if ((fields = getDeclaredSerialFields(cl)) == null) {
fields = getDefaultSerialFields(cl);
}
@ -2438,4 +2512,115 @@ public class ObjectStreamClass implements Serializable {
}
}
}
/** Record specific support for retrieving and binding stream field values. */
static final class RecordSupport {
/** Binds the given stream field values to the given method handle. */
@SuppressWarnings("preview")
static MethodHandle bindCtrValues(MethodHandle ctrMH,
ObjectStreamClass desc,
ObjectInputStream.FieldValues fieldValues) {
RecordComponent[] recordComponents;
try {
Class<?> cls = desc.forClass();
PrivilegedExceptionAction<RecordComponent[]> pa = cls::getRecordComponents;
recordComponents = AccessController.doPrivileged(pa);
} catch (PrivilegedActionException e) {
throw new InternalError(e.getCause());
}
Object[] args = new Object[recordComponents.length];
for (int i = 0; i < recordComponents.length; i++) {
String name = recordComponents[i].getName();
Class<?> type= recordComponents[i].getType();
Object o = streamFieldValue(name, type, desc, fieldValues);
args[i] = o;
}
return MethodHandles.insertArguments(ctrMH, 0, args);
}
/** Returns the number of primitive fields for the given descriptor. */
private static int numberPrimValues(ObjectStreamClass desc) {
ObjectStreamField[] fields = desc.getFields();
int primValueCount = 0;
for (int i = 0; i < fields.length; i++) {
if (fields[i].isPrimitive())
primValueCount++;
else
break; // can be no more
}
return primValueCount;
}
/** Returns the default value for the given type. */
private static Object defaultValueFor(Class<?> pType) {
if (pType == Integer.TYPE)
return 0;
else if (pType == Byte.TYPE)
return (byte)0;
else if (pType == Long.TYPE)
return 0L;
else if (pType == Float.TYPE)
return 0.0f;
else if (pType == Double.TYPE)
return 0.0d;
else if (pType == Short.TYPE)
return (short)0;
else if (pType == Character.TYPE)
return '\u0000';
else if (pType == Boolean.TYPE)
return false;
else
return null;
}
/**
* Returns the stream field value for the given name. The default value
* for the given type is returned if the field value is absent.
*/
private static Object streamFieldValue(String pName,
Class<?> pType,
ObjectStreamClass desc,
ObjectInputStream.FieldValues fieldValues) {
ObjectStreamField[] fields = desc.getFields();
for (int i = 0; i < fields.length; i++) {
ObjectStreamField f = fields[i];
String fName = f.getName();
if (!fName.equals(pName))
continue;
Class<?> fType = f.getField().getType();
if (!pType.isAssignableFrom(fType))
throw new InternalError(fName + " unassignable, pType:" + pType + ", fType:" + fType);
if (f.isPrimitive()) {
if (pType == Integer.TYPE)
return Bits.getInt(fieldValues.primValues, f.getOffset());
else if (fType == Byte.TYPE)
return fieldValues.primValues[f.getOffset()];
else if (fType == Long.TYPE)
return Bits.getLong(fieldValues.primValues, f.getOffset());
else if (fType == Float.TYPE)
return Bits.getFloat(fieldValues.primValues, f.getOffset());
else if (fType == Double.TYPE)
return Bits.getDouble(fieldValues.primValues, f.getOffset());
else if (fType == Short.TYPE)
return Bits.getShort(fieldValues.primValues, f.getOffset());
else if (fType == Character.TYPE)
return Bits.getChar(fieldValues.primValues, f.getOffset());
else if (fType == Boolean.TYPE)
return Bits.getBoolean(fieldValues.primValues, f.getOffset());
else
throw new InternalError("Unexpected type: " + fType);
} else { // reference
return fieldValues.objValues[i - numberPrimValues(desc)];
}
}
return defaultValueFor(pType);
}
}
}

View file

@ -46,6 +46,7 @@ import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.lang.reflect.RecordComponent;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.constant.Constable;
@ -2259,6 +2260,68 @@ public final class Class<T> implements java.io.Serializable,
return copyFields(privateGetDeclaredFields(false));
}
/**
* {@preview Associated with records, a preview feature of the Java language.
*
* This method is associated with <i>records</i>, a preview
* feature of the Java language. Preview features
* may be removed in a future release, or upgraded to permanent
* features of the Java language.}
*
* Returns an array containing {@code RecordComponent} objects reflecting all the
* declared record components of the record represented by this {@code Class} object.
* The components are returned in the same order that they are declared in the
* record header.
*
* @return The array of {@code RecordComponent} objects representing all the
* record components of this record. The array is empty if this class
* is not a record, or if this class is a record with no components.
* @throws SecurityException
* If a security manager, <i>s</i>, is present and any of the
* following conditions is met:
*
* <ul>
*
* <li> the caller's class loader is not the same as the
* class loader of this class and invocation of
* {@link SecurityManager#checkPermission
* s.checkPermission} method with
* {@code RuntimePermission("accessDeclaredMembers")}
* denies access to the declared methods within this class
*
* <li> the caller's class loader is not the same as or an
* ancestor of the class loader for the current class and
* invocation of {@link SecurityManager#checkPackageAccess
* s.checkPackageAccess()} denies access to the package
* of this class
*
* </ul>
*
* @jls 8.10 Record Types
* @since 14
*/
@jdk.internal.PreviewFeature(feature=jdk.internal.PreviewFeature.Feature.RECORDS,
essentialAPI=false)
@SuppressWarnings("preview")
@CallerSensitive
public RecordComponent[] getRecordComponents() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
}
if (isPrimitive() || isArray()) {
return new RecordComponent[0];
}
Object[] recordComponents = getRecordComponents0();
if (recordComponents == null || recordComponents.length == 0) {
return new RecordComponent[0];
}
RecordComponent[] result = new RecordComponent[recordComponents.length];
for (int i = 0; i < recordComponents.length; i++) {
result[i] = (RecordComponent)recordComponents[i];
}
return result;
}
/**
* Returns an array containing {@code Method} objects reflecting all the
@ -3417,6 +3480,8 @@ public final class Class<T> implements java.io.Serializable,
private native Method[] getDeclaredMethods0(boolean publicOnly);
private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
private native Class<?>[] getDeclaredClasses0();
private native Object[] getRecordComponents0();
private native boolean isRecord0();
/**
* Helper method to get the method name from arguments.
@ -3525,6 +3590,29 @@ public final class Class<T> implements java.io.Serializable,
this.getSuperclass() == java.lang.Enum.class;
}
/**
* {@preview Associated with records, a preview feature of the Java language.
*
* This method is associated with <i>records</i>, a preview
* feature of the Java language. Preview features
* may be removed in a future release, or upgraded to permanent
* features of the Java language.}
*
* Returns {@code true} if and only if this class is a record class.
* It returns {@code false} otherwise. Note that class {@link Record} is not a
* record type and thus invoking this method on class {@link java.lang.Record}
* returns {@code false}.
*
* @return true if and only if this class is a record class
* @jls 8.10 Record Types
* @since 14
*/
@jdk.internal.PreviewFeature(feature=jdk.internal.PreviewFeature.Feature.RECORDS,
essentialAPI=false)
public boolean isRecord() {
return isRecord0();
}
// Fetches the factory for reflective objects
private static ReflectionFactory getReflectionFactory() {
if (reflectionFactory == null) {

View file

@ -0,0 +1,154 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
/**
* {@preview Associated with records, a preview feature of the Java language.
*
* This class is associated with <i>records</i>, a preview
* feature of the Java language. Programs can only use this
* class when preview features are enabled. Preview features
* may be removed in a future release, or upgraded to permanent
* features of the Java language.}
*
* This is the common base class of all Java language record classes.
*
* <p>More information about records, including descriptions of the
* implicitly declared methods synthesized by the compiler, can be
* found in section 8.10 of
* <cite>The Java&trade; Language Specification</cite>.
*
* <p>A <em>record class</em> is a shallowly immutable, transparent carrier for
* a fixed set of values, called the <em>record components</em>. The Java&trade;
* language provides concise syntax for declaring record classes, whereby the
* record components are declared in the record header. The list of record
* components declared in the record header form the <em>record descriptor</em>.
*
* <p>A record class has the following mandated members: a public <em>canonical
* constructor</em>, whose descriptor is the same as the record descriptor;
* a private final field corresponding to each component, whose name and
* type are the same as that of the component; a public accessor method
* corresponding to each component, whose name and return type are the same as
* that of the component. If not explicitly declared in the body of the record,
* implicit implementations for these members are provided.
*
* <p>The implicit declaration of the canonical constructor initializes the
* component fields from the corresponding constructor arguments. The implicit
* declaration of the accessor methods returns the value of the corresponding
* component field. The implicit declaration of the {@link Object#equals(Object)},
* {@link Object#hashCode()}, and {@link Object#toString()} methods are derived
* from all of the component fields.
*
* <p>The primary reasons to provide an explicit declaration for the
* canonical constructor or accessor methods are to validate constructor
* arguments, perform defensive copies on mutable components, or normalize groups
* of components (such as reducing a rational number to lowest terms.)
*
* <p>For all record classes, the following invariant must hold: if a record R's
* components are {@code c1, c2, ... cn}, then if a record instance is copied
* as follows:
* <pre>
* R copy = new R(r.c1(), r.c2(), ..., r.cn());
* </pre>
* then it must be the case that {@code r.equals(copy)}.
*
* @apiNote
* A record class that {@code implements} {@link java.io.Serializable} is said
* to be a <i>serializable record</i>. Serializable records are serialized and
* deserialized differently than ordinary serializable objects. During
* deserialization the record's canonical constructor is invoked to construct
* the record object. Certain serialization-related methods, such as readObject
* and writeObject, are ignored for serializable records. More information about
* serializable records can be found in
* <a href="{@docRoot}/java.base/java/io/ObjectInputStream.html#record-serialization">record serialization</a>.
*
* @jls 8.10 Record Types
* @since 14
*/
@jdk.internal.PreviewFeature(feature=jdk.internal.PreviewFeature.Feature.RECORDS,
essentialAPI=true)
public abstract class Record {
/**
* Indicates whether some other object is "equal to" this one. In addition
* to the general contract of {@link Object#equals(Object)},
* record classes must further participate in the invariant that when
* a record instance is "copied" by passing the result of the record component
* accessor methods to the canonical constructor, as follows:
* <pre>
* R copy = new R(r.c1(), r.c2(), ..., r.cn());
* </pre>
* then it must be the case that {@code r.equals(copy)}.
*
* @implSpec
* The implicitly provided implementation returns {@code true} if and
* only if the argument is an instance of the same record type as this object,
* and each component of this record is equal to the corresponding component
* of the argument, according to {@link java.util.Objects#equals(Object,Object)}
* for components whose types are reference types, and according to the semantics
* of the {@code equals} method on the corresponding primitive wrapper type.
*
* @see java.util.Objects#equals(Object,Object)
*
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
*/
@Override
public abstract boolean equals(Object obj);
/**
* Obeys the general contract of {@link Object#hashCode Object.hashCode}.
*
* @implSpec
* The implicitly provided implementation returns a hash code value derived
* by combining the hash code value for all the components, according to
* {@link Object#hashCode()} for components whose types are reference types,
* or the primitive wrapper hash code for components whose types are primitive
* types.
*
* @see Object#hashCode()
*
* @return a hash code value for this object.
*/
@Override
public abstract int hashCode();
/**
* Obeys the general contract of {@link Object#toString Object.toString}.
*
* @implSpec
* The implicitly provided implementation returns a string that is derived
* from the name of the record class and the names and string representations
* of all the components, according to {@link Object#toString()} for components
* whose types are reference types, and the primitive wrapper {@code toString}
* method for components whose types are primitive types.
*
* @see Object#toString()
*
* @return a string representation of the object.
*/
@Override
public abstract String toString();
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -114,5 +114,25 @@ public enum ElementType {
*
* @since 9
*/
MODULE
MODULE,
/**
* {@preview Associated with records, a preview feature of the Java language.
*
* This constant is associated with <i>records</i>, a preview
* feature of the Java language. Programs can only use this
* constant when preview features are enabled. Preview features
* may be removed in a future release, or upgraded to permanent
* features of the Java language.}
*
* Record component
*
* @jls 8.10.3 Record Members
* @jls 9.7.4 Where Annotations May Appear
*
* @since 14
*/
@jdk.internal.PreviewFeature(feature=jdk.internal.PreviewFeature.Feature.RECORDS,
essentialAPI=true)
RECORD_COMPONENT;
}

View file

@ -0,0 +1,254 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.reflect;
import jdk.internal.access.SharedSecrets;
import sun.reflect.annotation.AnnotationParser;
import sun.reflect.annotation.TypeAnnotation;
import sun.reflect.annotation.TypeAnnotationParser;
import sun.reflect.generics.factory.CoreReflectionFactory;
import sun.reflect.generics.factory.GenericsFactory;
import sun.reflect.generics.repository.FieldRepository;
import sun.reflect.generics.scope.ClassScope;
import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.Objects;
/**
* {@preview Associated with records, a preview feature of the Java language.
*
* This class is associated with <i>records</i>, a preview
* feature of the Java language. Preview features
* may be removed in a future release, or upgraded to permanent
* features of the Java language.}
*
* A {@code RecordComponent} provides information about, and dynamic access to, a
* component of a record class.
*
* @see Class#getRecordComponents()
* @see java.lang.Record
* @jls 8.10 Record Types
* @since 14
*/
@jdk.internal.PreviewFeature(feature=jdk.internal.PreviewFeature.Feature.RECORDS,
essentialAPI=false)
public final class RecordComponent implements AnnotatedElement {
// declaring class
private Class<?> clazz;
private String name;
private Class<?> type;
private Method accessor;
private String signature;
// generic info repository; lazily initialized
private transient FieldRepository genericInfo;
private byte[] annotations;
private byte[] typeAnnotations;
@SuppressWarnings("preview")
private RecordComponent root;
// only the JVM can create record components
private RecordComponent() {}
/**
* Returns the name of this record component.
*
* @return the name of this record component
*/
public String getName() {
return name;
}
/**
* Returns a {@code Class} that identifies the declared type for this
* record component.
*
* @return a {@code Class} identifying the declared type of the component
* represented by this record component
*/
public Class<?> getType() {
return type;
}
/**
* Returns a {@code String} that describes the generic type signature for
* this record component.
*
* @return a {@code String} that describes the generic type signature for
* this record component
*
* @jvms 4.7.9.1 Signatures
*/
public String getGenericSignature() {
return signature;
}
/**
* Returns a {@code Type} object that represents the declared type for
* this record component.
*
* <p>If the declared type of the record component is a parameterized type,
* the {@code Type} object returned reflects the actual type arguments used
* in the source code.
*
* <p>If the type of the underlying record component is a type variable or a
* parameterized type, it is created. Otherwise, it is resolved.
*
* @return a {@code Type} object that represents the declared type for
* this record component
* @throws GenericSignatureFormatError if the generic record component
* signature does not conform to the format specified in
* <cite>The Java&trade; Virtual Machine Specification</cite>
* @throws TypeNotPresentException if the generic type
* signature of the underlying record component refers to a non-existent
* type declaration
* @throws MalformedParameterizedTypeException if the generic
* signature of the underlying record component refers to a parameterized
* type that cannot be instantiated for any reason
*/
public Type getGenericType() {
if (getGenericSignature() != null)
return getGenericInfo().getGenericType();
else
return getType();
}
// Accessor for generic info repository
private FieldRepository getGenericInfo() {
// lazily initialize repository if necessary
if (genericInfo == null) {
// create and cache generic info repository
genericInfo = FieldRepository.make(getGenericSignature(), getFactory());
}
return genericInfo; //return cached repository
}
// Accessor for factory
private GenericsFactory getFactory() {
Class<?> c = getDeclaringRecord();
// create scope and factory
return CoreReflectionFactory.make(c, ClassScope.make(c));
}
/**
* Returns an {@code AnnotatedType} object that represents the use of a type to specify
* the declared type of this record component.
*
* @return an object representing the declared type of this record component
*/
public AnnotatedType getAnnotatedType() {
return TypeAnnotationParser.buildAnnotatedType(typeAnnotations,
SharedSecrets.getJavaLangAccess().
getConstantPool(getDeclaringRecord()),
this,
getDeclaringRecord(),
getGenericType(),
TypeAnnotation.TypeAnnotationTarget.FIELD);
}
/**
* Returns a {@code Method} that represents the accessor for this record
* component.
*
* @return a {@code Method} that represents the accessor for this record
* component
*/
public Method getAccessor() {
return accessor;
}
/**
* @throws NullPointerException {@inheritDoc}
*/
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
Objects.requireNonNull(annotationClass);
return annotationClass.cast(declaredAnnotations().get(annotationClass));
}
private transient volatile Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
private Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
Map<Class<? extends Annotation>, Annotation> declAnnos;
if ((declAnnos = declaredAnnotations) == null) {
synchronized (this) {
if ((declAnnos = declaredAnnotations) == null) {
@SuppressWarnings("preview")
RecordComponent root = this.root;
if (root != null) {
declAnnos = root.declaredAnnotations();
} else {
declAnnos = AnnotationParser.parseAnnotations(
annotations,
SharedSecrets.getJavaLangAccess()
.getConstantPool(getDeclaringRecord()),
getDeclaringRecord());
}
declaredAnnotations = declAnnos;
}
}
}
return declAnnos;
}
/**
* {@inheritDoc}
*/
@Override
public Annotation[] getAnnotations() {
return getDeclaredAnnotations();
}
/**
* {@inheritDoc}
*/
@Override
public Annotation[] getDeclaredAnnotations() { return AnnotationParser.toArray(declaredAnnotations()); }
/**
* Returns a string describing this record component. The format is
* the record component type, followed by a space, followed by the name
* of the record component.
* For example:
* <pre>
* String name
* int age
* </pre>
*
* @return a string describing this record component
*/
public String toString() {
return (getType().getTypeName() + " " + getName());
}
/**
* Returns the record class which declares this record component.
*
* @return The record class declaring this record component.
*/
public Class<?> getDeclaringRecord() {
return clazz;
}
}

View file

@ -0,0 +1,375 @@
/*
* Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.runtime;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.TypeDescriptor;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
/**
* {@preview Associated with records, a preview feature of the Java language.
*
* This class is associated with <i>records</i>, a preview
* feature of the Java language. Preview features
* may be removed in a future release, or upgraded to permanent
* features of the Java language.}
*
* Bootstrap methods for state-driven implementations of core methods,
* including {@link Object#equals(Object)}, {@link Object#hashCode()}, and
* {@link Object#toString()}. These methods may be used, for example, by
* Java&trade; compiler implementations to implement the bodies of {@link Object}
* methods for record classes.
*
* @since 14
*/
@jdk.internal.PreviewFeature(feature=jdk.internal.PreviewFeature.Feature.RECORDS,
essentialAPI=false)
public class ObjectMethods {
private ObjectMethods() { }
private static final MethodType DESCRIPTOR_MT = MethodType.methodType(MethodType.class);
private static final MethodType NAMES_MT = MethodType.methodType(List.class);
private static final MethodHandle FALSE = MethodHandles.constant(boolean.class, false);
private static final MethodHandle TRUE = MethodHandles.constant(boolean.class, true);
private static final MethodHandle ZERO = MethodHandles.constant(int.class, 0);
private static final MethodHandle CLASS_IS_INSTANCE;
private static final MethodHandle OBJECT_EQUALS;
private static final MethodHandle OBJECTS_EQUALS;
private static final MethodHandle OBJECTS_HASHCODE;
private static final MethodHandle OBJECTS_TOSTRING;
private static final MethodHandle OBJECT_EQ;
private static final MethodHandle OBJECT_HASHCODE;
private static final MethodHandle OBJECT_TO_STRING;
private static final MethodHandle STRING_FORMAT;
private static final MethodHandle HASH_COMBINER;
private static final HashMap<Class<?>, MethodHandle> primitiveEquals = new HashMap<>();
private static final HashMap<Class<?>, MethodHandle> primitiveHashers = new HashMap<>();
private static final HashMap<Class<?>, MethodHandle> primitiveToString = new HashMap<>();
static {
try {
@SuppressWarnings("preview")
Class<ObjectMethods> OBJECT_METHODS_CLASS = ObjectMethods.class;
MethodHandles.Lookup publicLookup = MethodHandles.publicLookup();
MethodHandles.Lookup lookup = MethodHandles.lookup();
ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override public ClassLoader run() { return ClassLoader.getPlatformClassLoader(); }
});
CLASS_IS_INSTANCE = publicLookup.findVirtual(Class.class, "isInstance",
MethodType.methodType(boolean.class, Object.class));
OBJECT_EQUALS = publicLookup.findVirtual(Object.class, "equals",
MethodType.methodType(boolean.class, Object.class));
OBJECT_HASHCODE = publicLookup.findVirtual(Object.class, "hashCode",
MethodType.fromMethodDescriptorString("()I", loader));
OBJECT_TO_STRING = publicLookup.findVirtual(Object.class, "toString",
MethodType.methodType(String.class));
STRING_FORMAT = publicLookup.findStatic(String.class, "format",
MethodType.methodType(String.class, String.class, Object[].class));
OBJECTS_EQUALS = publicLookup.findStatic(Objects.class, "equals",
MethodType.methodType(boolean.class, Object.class, Object.class));
OBJECTS_HASHCODE = publicLookup.findStatic(Objects.class, "hashCode",
MethodType.methodType(int.class, Object.class));
OBJECTS_TOSTRING = publicLookup.findStatic(Objects.class, "toString",
MethodType.methodType(String.class, Object.class));
OBJECT_EQ = lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
MethodType.methodType(boolean.class, Object.class, Object.class));
HASH_COMBINER = lookup.findStatic(OBJECT_METHODS_CLASS, "hashCombiner",
MethodType.fromMethodDescriptorString("(II)I", loader));
primitiveEquals.put(byte.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
MethodType.fromMethodDescriptorString("(BB)Z", loader)));
primitiveEquals.put(short.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
MethodType.fromMethodDescriptorString("(SS)Z", loader)));
primitiveEquals.put(char.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
MethodType.fromMethodDescriptorString("(CC)Z", loader)));
primitiveEquals.put(int.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
MethodType.fromMethodDescriptorString("(II)Z", loader)));
primitiveEquals.put(long.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
MethodType.fromMethodDescriptorString("(JJ)Z", loader)));
primitiveEquals.put(float.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
MethodType.fromMethodDescriptorString("(FF)Z", loader)));
primitiveEquals.put(double.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
MethodType.fromMethodDescriptorString("(DD)Z", loader)));
primitiveEquals.put(boolean.class, lookup.findStatic(OBJECT_METHODS_CLASS, "eq",
MethodType.fromMethodDescriptorString("(ZZ)Z", loader)));
primitiveHashers.put(byte.class, lookup.findStatic(Byte.class, "hashCode",
MethodType.fromMethodDescriptorString("(B)I", loader)));
primitiveHashers.put(short.class, lookup.findStatic(Short.class, "hashCode",
MethodType.fromMethodDescriptorString("(S)I", loader)));
primitiveHashers.put(char.class, lookup.findStatic(Character.class, "hashCode",
MethodType.fromMethodDescriptorString("(C)I", loader)));
primitiveHashers.put(int.class, lookup.findStatic(Integer.class, "hashCode",
MethodType.fromMethodDescriptorString("(I)I", loader)));
primitiveHashers.put(long.class, lookup.findStatic(Long.class, "hashCode",
MethodType.fromMethodDescriptorString("(J)I", loader)));
primitiveHashers.put(float.class, lookup.findStatic(Float.class, "hashCode",
MethodType.fromMethodDescriptorString("(F)I", loader)));
primitiveHashers.put(double.class, lookup.findStatic(Double.class, "hashCode",
MethodType.fromMethodDescriptorString("(D)I", loader)));
primitiveHashers.put(boolean.class, lookup.findStatic(Boolean.class, "hashCode",
MethodType.fromMethodDescriptorString("(Z)I", loader)));
primitiveToString.put(byte.class, lookup.findStatic(Byte.class, "toString",
MethodType.methodType(String.class, byte.class)));
primitiveToString.put(short.class, lookup.findStatic(Short.class, "toString",
MethodType.methodType(String.class, short.class)));
primitiveToString.put(char.class, lookup.findStatic(Character.class, "toString",
MethodType.methodType(String.class, char.class)));
primitiveToString.put(int.class, lookup.findStatic(Integer.class, "toString",
MethodType.methodType(String.class, int.class)));
primitiveToString.put(long.class, lookup.findStatic(Long.class, "toString",
MethodType.methodType(String.class, long.class)));
primitiveToString.put(float.class, lookup.findStatic(Float.class, "toString",
MethodType.methodType(String.class, float.class)));
primitiveToString.put(double.class, lookup.findStatic(Double.class, "toString",
MethodType.methodType(String.class, double.class)));
primitiveToString.put(boolean.class, lookup.findStatic(Boolean.class, "toString",
MethodType.methodType(String.class, boolean.class)));
}
catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
private static int hashCombiner(int x, int y) {
return x*31 + y;
}
private static boolean eq(Object a, Object b) { return a == b; }
private static boolean eq(byte a, byte b) { return a == b; }
private static boolean eq(short a, short b) { return a == b; }
private static boolean eq(char a, char b) { return a == b; }
private static boolean eq(int a, int b) { return a == b; }
private static boolean eq(long a, long b) { return a == b; }
private static boolean eq(float a, float b) { return Float.compare(a, b) == 0; }
private static boolean eq(double a, double b) { return Double.compare(a, b) == 0; }
private static boolean eq(boolean a, boolean b) { return a == b; }
/** Get the method handle for combining two values of a given type */
private static MethodHandle equalator(Class<?> clazz) {
return (clazz.isPrimitive()
? primitiveEquals.get(clazz)
: OBJECTS_EQUALS.asType(MethodType.methodType(boolean.class, clazz, clazz)));
}
/** Get the hasher for a value of a given type */
private static MethodHandle hasher(Class<?> clazz) {
return (clazz.isPrimitive()
? primitiveHashers.get(clazz)
: OBJECTS_HASHCODE.asType(MethodType.methodType(int.class, clazz)));
}
/** Get the stringifier for a value of a given type */
private static MethodHandle stringifier(Class<?> clazz) {
return (clazz.isPrimitive()
? primitiveToString.get(clazz)
: OBJECTS_TOSTRING.asType(MethodType.methodType(String.class, clazz)));
}
/**
* Generates a method handle for the {@code equals} method for a given data class
* @param receiverClass the data class
* @param getters the list of getters
* @return the method handle
*/
private static MethodHandle makeEquals(Class<?> receiverClass,
List<MethodHandle> getters) {
MethodType rr = MethodType.methodType(boolean.class, receiverClass, receiverClass);
MethodType ro = MethodType.methodType(boolean.class, receiverClass, Object.class);
MethodHandle instanceFalse = MethodHandles.dropArguments(FALSE, 0, receiverClass, Object.class); // (RO)Z
MethodHandle instanceTrue = MethodHandles.dropArguments(TRUE, 0, receiverClass, Object.class); // (RO)Z
MethodHandle isSameObject = OBJECT_EQ.asType(ro); // (RO)Z
MethodHandle isInstance = MethodHandles.dropArguments(CLASS_IS_INSTANCE.bindTo(receiverClass), 0, receiverClass); // (RO)Z
MethodHandle accumulator = MethodHandles.dropArguments(TRUE, 0, receiverClass, receiverClass); // (RR)Z
for (MethodHandle getter : getters) {
MethodHandle equalator = equalator(getter.type().returnType()); // (TT)Z
MethodHandle thisFieldEqual = MethodHandles.filterArguments(equalator, 0, getter, getter); // (RR)Z
accumulator = MethodHandles.guardWithTest(thisFieldEqual, accumulator, instanceFalse.asType(rr));
}
return MethodHandles.guardWithTest(isSameObject,
instanceTrue,
MethodHandles.guardWithTest(isInstance, accumulator.asType(ro), instanceFalse));
}
/**
* Generates a method handle for the {@code hashCode} method for a given data class
* @param receiverClass the data class
* @param getters the list of getters
* @return the method handle
*/
private static MethodHandle makeHashCode(Class<?> receiverClass,
List<MethodHandle> getters) {
MethodHandle accumulator = MethodHandles.dropArguments(ZERO, 0, receiverClass); // (R)I
// @@@ Use loop combinator instead?
for (MethodHandle getter : getters) {
MethodHandle hasher = hasher(getter.type().returnType()); // (T)I
MethodHandle hashThisField = MethodHandles.filterArguments(hasher, 0, getter); // (R)I
MethodHandle combineHashes = MethodHandles.filterArguments(HASH_COMBINER, 0, accumulator, hashThisField); // (RR)I
accumulator = MethodHandles.permuteArguments(combineHashes, accumulator.type(), 0, 0); // adapt (R)I to (RR)I
}
return accumulator;
}
/**
* Generates a method handle for the {@code toString} method for a given data class
* @param receiverClass the data class
* @param getters the list of getters
* @param names the names
* @return the method handle
*/
private static MethodHandle makeToString(Class<?> receiverClass,
List<MethodHandle> getters,
List<String> names) {
// This is a pretty lousy algorithm; we spread the receiver over N places,
// apply the N getters, apply N toString operations, and concat the result with String.format
// Better to use String.format directly, or delegate to StringConcatFactory
// Also probably want some quoting around String components
assert getters.size() == names.size();
int[] invArgs = new int[getters.size()];
Arrays.fill(invArgs, 0);
MethodHandle[] filters = new MethodHandle[getters.size()];
StringBuilder sb = new StringBuilder();
sb.append(receiverClass.getSimpleName()).append("[");
for (int i=0; i<getters.size(); i++) {
MethodHandle getter = getters.get(i); // (R)T
MethodHandle stringify = stringifier(getter.type().returnType()); // (T)String
MethodHandle stringifyThisField = MethodHandles.filterArguments(stringify, 0, getter); // (R)String
filters[i] = stringifyThisField;
sb.append(names.get(i)).append("=%s");
if (i != getters.size() - 1)
sb.append(", ");
}
sb.append(']');
String formatString = sb.toString();
MethodHandle formatter = MethodHandles.insertArguments(STRING_FORMAT, 0, formatString)
.asCollector(String[].class, getters.size()); // (R*)String
if (getters.size() == 0) {
// Add back extra R
formatter = MethodHandles.dropArguments(formatter, 0, receiverClass);
}
else {
MethodHandle filtered = MethodHandles.filterArguments(formatter, 0, filters);
formatter = MethodHandles.permuteArguments(filtered, MethodType.methodType(String.class, receiverClass), invArgs);
}
return formatter;
}
/**
* Bootstrap method to generate the {@link Object#equals(Object)},
* {@link Object#hashCode()}, and {@link Object#toString()} methods, based
* on a description of the component names and accessor methods, for either
* {@code invokedynamic} call sites or dynamic constant pool entries.
*
* For more detail on the semantics of the generated methods see the specification
* of {@link java.lang.Record#equals(Object)}, {@link java.lang.Record#hashCode()} and
* {@link java.lang.Record#toString()}.
*
*
* @param lookup Every bootstrap method is expected to have a {@code lookup}
* which usually represents a lookup context with the
* accessibility privileges of the caller. This is because
* {@code invokedynamic} call sites always provide a {@code lookup}
* to the corresponding bootstrap method, but this method just
* ignores the {@code lookup} parameter
* @param methodName the name of the method to generate, which must be one of
* {@code "equals"}, {@code "hashCode"}, or {@code "toString"}
* @param type a {@link MethodType} corresponding the descriptor type
* for the method, which must correspond to the descriptor
* for the corresponding {@link Object} method, if linking
* an {@code invokedynamic} call site, or the
* constant {@code MethodHandle.class}, if linking a
* dynamic constant
* @param recordClass the record class hosting the record components
* @param names the list of component names, joined into a string
* separated by ";", or the empty string if there are no
* components. Maybe be null, if the {@code methodName}
* is {@code "equals"} or {@code "hashCode"}.
* @param getters method handles for the accessor methods for the components
* @return a call site if invoked by indy, or a method handle
* if invoked by a condy
* @throws IllegalArgumentException if the bootstrap arguments are invalid
* or inconsistent
* @throws Throwable if any exception is thrown during call site construction
*/
public static Object bootstrap(MethodHandles.Lookup lookup, String methodName, TypeDescriptor type,
Class<?> recordClass,
String names,
MethodHandle... getters) throws Throwable {
MethodType methodType;
if (type instanceof MethodType)
methodType = (MethodType) type;
else {
methodType = null;
if (!MethodHandle.class.equals(type))
throw new IllegalArgumentException(type.toString());
}
List<MethodHandle> getterList = List.of(getters);
MethodHandle handle;
switch (methodName) {
case "equals":
if (methodType != null && !methodType.equals(MethodType.methodType(boolean.class, recordClass, Object.class)))
throw new IllegalArgumentException("Bad method type: " + methodType);
handle = makeEquals(recordClass, getterList);
return methodType != null ? new ConstantCallSite(handle) : handle;
case "hashCode":
if (methodType != null && !methodType.equals(MethodType.methodType(int.class, recordClass)))
throw new IllegalArgumentException("Bad method type: " + methodType);
handle = makeHashCode(recordClass, getterList);
return methodType != null ? new ConstantCallSite(handle) : handle;
case "toString":
if (methodType != null && !methodType.equals(MethodType.methodType(String.class, recordClass)))
throw new IllegalArgumentException("Bad method type: " + methodType);
List<String> nameList = "".equals(names) ? List.of() : List.of(names.split(";"));
if (nameList.size() != getterList.size())
throw new IllegalArgumentException("Name list and accessor list do not match");
handle = makeToString(recordClass, getterList, nameList);
return methodType != null ? new ConstantCallSite(handle) : handle;
default:
throw new IllegalArgumentException(methodName);
}
}
}

View file

@ -0,0 +1,33 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* The {@code java.lang.runtime} package provides low-level runtime support
* for the Java language.
*
* @since 14
*/
package java.lang.runtime;