Java Record:修订间差异
Created page with " <syntaxhighlight lang="java"> public class Test { record Person(String firstName, String lastName, int age) { } public static void main(String[] args) { var me = new Person("Riguz", "Lee", 20); System.out.println(me); } } </syntaxhighlight> Output: <syntaxhighlight lang="java"> Person[firstName=Riguz, lastName=Lee, age=20] </syntaxhighlight> Category:Java" |
无编辑摘要 |
||
第15行: | 第15行: | ||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
Person[firstName=Riguz, lastName=Lee, age=20] | Person[firstName=Riguz, lastName=Lee, age=20] | ||
</syntaxhighlight> | |||
* Record是不可变对象 | |||
* 自动实现了构造方法,equlas,hashcode,toString | |||
* 可以实现接口、添加方法 | |||
* 可以添加构造器的检测: | |||
<syntaxhighlight lang="java"> | |||
public class Test { | |||
record Person(String firstName, String lastName, int age) { | |||
public Person { | |||
if(age < 0 || age > 100) | |||
throw new IllegalArgumentException("Age is invalid"); | |||
} | |||
} | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
[[Category:Java]] | [[Category:Java]] |
2023年9月25日 (一) 05:37的最新版本
public class Test {
record Person(String firstName, String lastName, int age) {
}
public static void main(String[] args) {
var me = new Person("Riguz", "Lee", 20);
System.out.println(me);
}
}
Output:
Person[firstName=Riguz, lastName=Lee, age=20]
- Record是不可变对象
- 自动实现了构造方法,equlas,hashcode,toString
- 可以实现接口、添加方法
- 可以添加构造器的检测:
public class Test {
record Person(String firstName, String lastName, int age) {
public Person {
if(age < 0 || age > 100)
throw new IllegalArgumentException("Age is invalid");
}
}
}