有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

C#和Java类属性之间有什么区别?

我只是想在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;}
    }   
}

共 (1) 个答案

  1. # 1 楼答案

    在Java中,不像在C#中那样,没有显式“声明属性”的语法方法。这并不意味着Java中不存在语义上的属性

    official docs开始:

    To define a property in a bean class, supply public getter and setter methods.

    以您的类为例,它在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,只需声明属性类型、名称和acessor,就可以减少人为错误的空间