Practical Java 16 value type record - 2. Basic usage of record

Full of dry goods 2021-04-16 13:52:05
practical java value type record


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

image

版权声明
本文为[Full of dry goods]所创,转载请带上原文链接,感谢
https://javamana.com/2021/04/20210416123923009Z.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云