In the last article actual combat Java 16 Value type Record - 1. Record And the underlying implementation of generating relevant bytecode based on precompilation in , We analyzed in detail Record Its own properties and methods and the underlying bytecode and implementation . Let's elaborate on this one Record The use of the class .

Make a statement Record

Record Sure As the top-level class of a single file , namely :

User.java file :

public record User(long id, String name, int age) {}

It's fine too As a member class , namely :

public class RecordTest {
public record User(long id, String name, int age) {}
}

It's fine too As a local class , namely :

public class RecordTest {
public void test() {
record Mail (long id, String content){}
Mail mail = new Mail(10, "content");
}
}

Out-of-service abstract modification Record class , There will be compilation errors .

It can be used final modification Record class , But it's not really necessary , because Record The class itself is final Of .

member Record class , And local Record class , Itself is static Of , It can also be used. static modification , But there is no need to .

Same as normal class ,Record Class can be public, protected, private modification , Or you can leave it alone , This is the package-private Of .

Different from the general class ,Record The immediate parent of a class is not java.lang.Object It is java.lang.Record. however ,Record Class cannot use extends, because Record Class cannot inherit any class .

Record Attributes of a class

commonly , stay Record The class declaration header specifies this Record What are the properties of the class

public record User(long id, String name, int age) {}

meanwhile , You can use annotations in the attribute list in the header :

@Target({ ElementType.RECORD_COMPONENT})
@Retention(RetentionPolicy.RUNTIME)
public @interface A {}
@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface B {} public record User(@A @B long id, String name, int age) {}

however , One thing to note , Here we get it through reflection id When you annotate , You need to get it in a corresponding way , Otherwise, you can't get , namely ElementType.FIELD adopt Field obtain ,ElementType.RECORD_COMPONENT adopt RecordComponent obtain :

Field[] fields = User.class.getDeclaredFields();
Annotation[] annotations = fields[0].getAnnotations(); // Get comments @B RecordComponent[] recordComponents = User.class.getRecordComponents();
annotations = recordComponents[0].getAnnotations(); // Get comments @A

Record The class body

Record Class properties must be declared in the header , stay Record Class bodies can only declare static properties

public record User(long id, String name, int age) {
static long anotherId;
}

Record Class bodies can declare member methods and static methods , Just like the general class . however Cannot declare abstract perhaps native Method

public record User(long id, String name, int age) {
public void test(){}
public static void test2(){}
}

Record Class bodies also cannot contain instance initialization blocks , for example :

public record User(@A @B long id, String name, int age) {
{
System.out.println(); // Compile exception
}
}

Record member

Record All member properties of , All are public final Not static Of , For each attribute , There is a corresponding method with no parameter return type as property type and method name as property name , That is to say, the property of accessor. The method mentioned above is getter The method is not very accurate , Because there is no get perhaps is It's just the pure property name as the method name .

If we specify this method ourselves , It's not automatically generated :

public record User(long id) {
@Override
public long id() {
return id;
}
}

If you don't specify it yourself , Then such a method will be generated automatically :

  1. The method name is the property name
  2. The return type is the corresponding property type
  3. It's a public Method , And no declaration throws any exception
  4. The method body returns the corresponding property
  5. If there are any comments on the attribute , If the annotation can be added to the method, it will also be added to the method automatically . for example :
public record User(@A @B long id, String name, int age) {}
@Target({
ElementType.RECORD_COMPONENT,
ElementType.METHOD,
})
@Retention(RetentionPolicy.RUNTIME)
public @interface A {}
@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface B {}

Here we get id() The annotation of this method will get the annotation @A

Method id = User.class.getDeclaredMethod("id");
Annotation[] idAnnotations = id.getAnnotations(); //@A

Because these methods are generated automatically , therefore Record The name of a member cannot be the same as Object Some of the above conditions are not met ( As mentioned above 6 strip ) The name of the method is the same , for example :

public record User(
int wait, // Compile error
int hashcode, // There's no mistake in this , because hashcode() Methods conform to the automatically generated accessor The limitations of .
int toString, // Compile error
int finalize // Compile error ) {
}

Record Class if not specified , The implementation is generated by default java.lang.Record Abstract method of , namely hashcode(), equals(), toStrng() These three methods . this The implementation of the three methods , It has been analyzed in detail in the first section , Here's a brief review of the main points :

  1. hashcode() Automatically generate bytecode when compiling , The core logic is based on ObjectMethods Of makeHashCode Method , The logic is to shift and combine the hash values of each attribute . Notice all the calls here ( Including for ObjectMethods And get each property ) It's all about using MethodHandle The implementation is similar to that of direct call .
  2. equals() Automatically generate bytecode when compiling , The core logic is based on ObjectMethods Of makeEquals Method , The logic is for two Record Object to determine whether each attribute is equal ( For reference types, use Objects.equals(), The original type uses ==), Notice all the calls here ( Including for ObjectMethods And get each property ) It's all about using MethodHandle The implementation is similar to that of direct call .
  3. toString() Automatically generate bytecode when compiling , The core logic is based on ObjectMethods Of makeToString Method , The logic is to combine the values of each attribute to form a string . Notice all the calls here ( Including for ObjectMethods And get each property ) It's all about using MethodHandle The implementation is similar to that of direct call .

Record Constructors

If no constructor is specified ,Record Class will automatically generate a constructor that takes all properties as parameters and assigns values to each property . We can declare constructors ourselves in two ways :

The first is to explicitly declare constructors that take all attributes as parameters and assign values to each attribute , This constructor needs to satisfy :

  1. Constructor parameters need to include all attributes ( The same name, the same type ), And in accordance with the Record Declaration order of class headers .
  2. You cannot declare that any exception is thrown ( Out of commission throws)
  3. No other constructors can be called ( I can't use this(xxx))
  4. The constructor needs to assign values to each property .

For other constructors , You need to explicitly call the constructor that contains all the properties

public record User(long id, String name, int age) {
public User(int age, long id) {
this(id, "name", age);
}
public User(long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}

The second is to state in a short way , for example :

public record User(long id, String name, int age) {
public User {
System.out.println("initialized");
id = 1000 + id;
name = "prefix_" + name;
age = 1 + age;
// After this , Assign values to each property
}
}

This approach is equivalent to omitting parameters and assigning values to each property , It's equivalent to inserting code at the beginning of this constructor .

WeChat search “ My programming meow ” Official account , Once a day , Easy to upgrade technology , Capture all kinds of offer

actual combat Java 16 Value type Record - 2. Record More related articles on the basic usage of

  1. JAVA The difference between median type and reference type ( Interviews often test )

    Reprint :https://www.cnblogs.com/1ming/p/5227944.html 1. JAVA The difference between median type and reference type ? [ Definition ] The reference type indicates that the data you operate on is the same , That is to say, when you pass a ...

  2. 【 turn 】Java Do you have value types ?

    Java Do you have value types ? Someone read my previous article 『Swift Language design errors 』, Ask me :“ You say? Java Only reference types (reference type), But according to Java Official documents of ,Java There are also value types ( ...

  3. java The difference between median type and reference type

    [ Definition ] The reference type indicates that the data you operate on is the same , That is, when you pass a parameter to another method , You change the value of this variable in another way , Then the value of the variable passed in by calling this method will also change . Value type means to copy a current variable and pass it to a method , When you ...

  4. java The relationship between median type and reference type

    Value type : Namely java Basic type .byte.short.int.long.float.char.double.boolean Reference type : class (class). Interface (Interface). Array (Array) ...

  5. Java The value type and reference type of

    One . Problem description A few days ago, because of a demand Bug. It's also very advanced when it comes to advanced points , It's easy to say white dot . In fact, it is a very simple Java The difference between the value type and the reference type at the beginning of the foundation . Just because of my own problems when developing , Leading to small problems . not so bad ...

  6. Controller in Action return type And its Page Jump usage

        •Controller in Action return type View – return   ViewResult, It is equivalent to returning a View page . -------------------------------- ...

  7. Learning record java Knowledge of value types and reference types

    1. Java The difference between median type and reference type ? [ Definition ] The reference type indicates that the data you operate on is the same , That is, when you pass a parameter to another method , You change the value of this variable in another way , Then the value of the variable passed in by calling this method will also change ...

  8. java The relationship between wrapper class and value type

    java Packaging is always confusing How does it relate to the value type ? This article will be int and Integer To explore the relationship between them java The value types are int short char boolean byte long fl ...

  9. PL/SQL aggregate ( One ): Record type (TYPE Type the name IS RECORD)

    Record type The definition of composite data type can be realized by using record type : Record types allow nesting : You can update data directly with record types . The problem of traditional operation about Oracle data type , The main use is VARCHAR2.NUMBER.DATE etc. ...

  10. Java Reference type variables in , object , Value type , Value passed , reference Differences and definitions

    One .Java What is a reference type variable in ? quote : That is to query by memory address        such as :String s = new String(); This is actually to allocate a memory space in the stack memory for s, In heap memory new One. Stri ...

Random recommendation

  1. D.T SOFTWARE (1) Software architecture live Q & a course

    Tonight's d.t Course 1 Project requirements PPTP Service construction completed PPTP Server building , The user redials to get a new IP after , Request to pull out PPTP VPN success , And get a new public network IP, And you can access the Internet through an agent .VNC Service installation users can use VN ...

  2. nsx-edge Virtual machine packet capture practice

    Edge Grab the bag Today when troubleshooting on the client , I need to perform packet capture on an edge services gateway in the environment . When diagnosing a series of different problems , It's often useful to perform package capture . To start package capture , You can jump to ESG In the console , Or as I did in this case ...

  3. hnsdfz -- 6.20 -- day5

    Today's topic of Zizhen ...... It's much more substantial than the last two days …… I've got a line tree , Also played a question to answer …… Although the segment tree doesn't know why 50->25, The data of the questions and answers are too watery 90+... I didn't think of any ideas , Brainless liver segment tree , No brain, no problem ...

  4. XOR+base64 encryption

    1.xor operation 1^0=1 0^0=0 1^1=0 23^32=55 55^32=23 23 Yes 32 The result of XOR operation twice is 23 2.XOR encryption set up key=[]byte{1,2,3,4,5,6},src= ...

  5. tp5 Generate small programs to promote two-dimensional code

    // Get user dealer information And generating generalized two-dimensional code public function qrcode() { // Get openid Find whether there is the user in the user table If not, refuse to generate QR code If yes, check whether the QR code has been generated If there is generation ...

  6. svn -- svn Installation and configuration

    1.SVN It is divided into server and client l  Server side :VisualSVN   SubVersion l  client :TortoiseSVN server http://www.visualsvn.com/ cli ...

  7. Warning: Data truncated for column 'xxxx' at row 1

    The problem was that I changed the column's length only in the program.I had to do either change the ...

  8. Python Common string operations

    1.strip.lstrip and rstrip describe : Used to remove the left and right sides of a string . On the left . The character specified on the right ( The default is white space , for example :/n, /r, /t, ' ') Or character sequence . grammar : str.strip([cha ...

  9. python Input And how to view documents Summary

    Python 2 Input summary in Please state the source of this article : Looking up at Daniel's little fresh 1.raw_input(prompt = None) And input(prompt = None) Both are default parameter types , This ginseng ...

  10. 46. Permutations Number of permutations

    46. Permutations subject Given a collection of distinct numbers, return all possible permutations. For ex ...