我只是试图在Java类上定义一个属性getter,并告诉他Java不使用getter和setter,事实上,它并没有"属性"。 (What is a virtual (derived) attribute in Java?)
C#和Java之间有什么区别"简单" /"价值" /"属性" /"属性"班级成员以及每种语言的选择有哪些优点/缺点?
以C#中的此属性用法为例:
public class Dude{
public string fName {get; set;} //this is what I mean by property
public string lName {get; set;}
public string fullName
{
get {return this.fName + " " + this.lName;}
}
}
答案 0 :(得分:4)
在Java中,您没有合成方式明确“声明属性”,就像在C#中一样。这并不意味着Java 语义中不存在属性。
要在bean类中定义属性,请提供 public getter和setter方法 。
所以,以你的类为例,它在Java中看起来像这样:
public class Dude{
public String fName;
public String lName;
public String getFName() {
return fName;
}
public void setFName(String fName) {
this.fName = fName;
}
public String getLName() {
return lName;
}
public void setLName(String lName) {
this.lName = lName;
}
public String getFullName() {
return this.fName + " " + this.lName;
}
}
如果您使用Java的反射API对其进行内省并操纵PropertyDescriptors,您会注意到它们将读/写操作委托给getter和setter:
BeanInfo info = Introspector.getBeanInfo(MyBean.class);
PropertyDescriptor[] pds = info.getPropertyDescriptors();
pds[0].getReadMethod().invoke(..); // Call to getFName()
pds[0].getWriteMethod().invoke(..); // Call to setFName()
除了从C#获得的语法糖之外,我相信这种Java方法的最大问题是容易出现代码错误。复制/粘贴代码并忘记实际更改操作变量非常容易。使用C#sugar,您只需声明属性Type,Name和Acessors,就可以减少人为错误的空间。