Kotlin调用Java中的Getter 和 Setter
在Java中遵循这样的约定: getter 方法无参数并以 get 开头,setter 方法单参数并以 set 开头。在 Kotlin 中我们可以直接表示为属性。 例如,我们写一个带setter和getter的Java类:
1. package com.easy.kotlin;
3. import java.util.Date;
5. public class Product {
6. Long id;
7. String name;
8. String category;
9. Date gmtCreated;
10. Date gmtModified;
12. public Long getId() {
13. return id;
14. }
16. public void setId(Long id) {
17. this.id = id;
18. }
20. public String getName() {
21. return name;
22. }
24. public void setName(String name) {
25. this.name = name;
26. }
28. public String getCategory() {
29. return category;
30. }
32. public void setCategory(String category) {
33. this.category = category;
34. }
36. public Date getGmtCreated() {
37. return gmtCreated;
38. }
40. public void setGmtCreated(Date gmtCreated) {
41. this.gmtCreated = gmtCreated;
42. }
44. public Date getGmtModified() {
45. return gmtModified;
46. }
48. public void setGmtModified(Date gmtModified) {
49. this.gmtModified = gmtModified;
50. }
51. }
然后,我们在Kotlin可以直接使用属性名字进行get和set操作:
1. @RunWith(JUnit4::class)
2. class ProductTest {
3. @Test fun testGetterSetter() {
4. val product = Product()
5. product.name = "账务系统"
6. product.category = "金融财务类"
7. product.gmtCreated = Date()
8. product.gmtModified = Date()
9. println(JSONUtils.toJsonString(product))
10. Assert.assertTrue(product.getName() == "账务系统")
11. Assert.assertTrue(product.name == "账务系统")
12. Assert.assertTrue(product.getCategory() == "金融财务类")
13. Assert.assertTrue(product.category == "金融财务类")
14. }
15. }
当然,我们还可以像在Java中一样,直接调用像product.getName()、product.setName(“Kotlin”)这样的getter、setter方法。
