Cer*_*rin 9 python java properties
我是Java的新手,我想创建一些在访问时动态计算的类变量,就像在Python中使用property()方法一样.但是,我不确定如何描述这个,所以谷歌搜索向我展示了很多关于Java"Property"类的内容,但这看起来并不是一回事.什么是Java的属性()的Java等价物?
Java语言中没有这样的工具.你必须自己明确地编写所有的getter和setter.像Eclipse这样的IDE可以为您生成这个样板代码.
例如 :
class Point{
private int x, y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public void setX(int x){
this.x = x;
}
public int getX(){
return x;
}
public void setY(int y){
this.y = y;
}
public int getY(){
return y;
}
}
Run Code Online (Sandbox Code Playgroud)
你可能想看看项目龙目岛提供了注解@Getter和@Setter是有点类似于Python的property.
使用Lombok,上面的示例简化为:
class Point{
@Getter @Setter private int x, y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2598 次 |
| 最近记录: |