Java 中的 getter/setter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/875033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:31:04  来源:igfitidea点击:

Getters/setters in Java

javaactionscript-3settergetteraccessor

提问by George Profenza

I'm new to Java, but have some OOP experience with ActionScript 3, so I'm trying to migrate relying on stuff I know.

我是 Java 新手,但对 ActionScript 3 有一些 OOP 经验,所以我正在尝试根据我知道的东西进行迁移。

In ActionScript 3 you can create getters and setters using the get and set keywords, meaning you create a method in the class and access data through a property of an instance of that class. I might sound complicated, but it's not. Here's an example:

在 ActionScript 3 中,您可以使用 get 和 set 关键字创建 getter 和 setter,这意味着您可以在类中创建一个方法并通过该类实例的属性访问数据。我可能听起来很复杂,但事实并非如此。下面是一个例子:

class Dummy{

    private var _name:String;

    public function Dummy(name:String=null){
        this._name = name;
    }

    //getter
    public function get name():String{
        return _name;
    }

    //setter
    public function set name(value:String):void{
    //do some validation if necessary
        _name = value;
    }

}

And I would access namein an object as:

我会name在一个对象中访问:

var dummy:Dummy = new Dummy("fred");
trace(dummy.name);//prints: fred
dummy.name = "lolo";//setter
trace(dummy.name);//getter

How would I do that in Java?

我将如何在 Java 中做到这一点?

Just having some public fields is out of the question. I've noticed that there is this convention of using get and set in front of methods, which I'm OK with.

仅仅拥有一些公共领域是不可能的。我注意到在方法前面有使用 get 和 set 的约定,我可以接受。

For example,

例如,

class Dummy{

    String _name;

    public void Dummy(){}

    public void Dummy(String name){
        _name = name;
    }

    public String getName(){
        return _name;
    }

    public void setName(String name){
        _name = name;
    }

}

Is there an equivalent of ActionScript 3 getter/setters in Java, as in accessing a private field as a field from an instance of the class, but having a method for implementing that internally in the class?

在 Java 中是否有等效于 ActionScript 3 的 getter/setter,比如从类的实例中访问私有字段作为字段,但有一个在类内部实现它的方法?

采纳答案by zenazn

Nope. AS3 getters and setters are an ECMAScript thing. In Java, you're stuck with the getVal() and setVal() style functions--there isn't any syntactic sugar to make things easy for you.

不。AS3 getter 和 setter 是 ECMAScript 的东西。在 Java 中,您被 getVal() 和 setVal() 风格的函数困住了——没有任何语法糖可以让您轻松完成任务。

I think Eclipse can help auto-generating those types of things though...

我认为 Eclipse 可以帮助自动生成这些类型的东西...

回答by coobird

In Java, the only option you have without exposing the internals of your object is to make your own getters and setters as you have in your example.

在 Java 中,不暴露对象内部结构的唯一选择是像示例中那样创建自己的 getter 和 setter。

The convention is to prepend getor setin front of the field which is being altered. So, as in your example, the field namewould have getNameand setNamemethods as their corresponding getter and setter, respectively.

约定是在要更改的字段之前get或之前set。因此,就像在您的示例中一样,该字段name将分别具有getNamesetName方法作为其相应的 getter 和 setter。

回答by Stephan202

Your Java code is fine, except that you would, want to make _nameprivate.

您的 Java 代码很好,只是您希望将其设为_nameprivate

There are no getand setkeywords in Java as in your AS3 example. Sorry, it doesn't get better than what you're doing already.

Java中没有像 AS3 示例中那样的getset关键字。对不起,它并没有比你已经在做的更好。

Corrected code:

更正的代码:

class Dummy {
  private String _name;

  public void Dummy() {}

  public void Dummy(String name) {
    setName(name);
  }

  public String getName() {
    return _name;
  }

  public void setName(String value) {
    _name = value;
  }
}

回答by Daniel Martin

Sadly, no, there isn't the equivalent language-level support in java.

可悲的是,不,java 中没有等效的语言级别支持。

The get* and set* patterns though are so established in java culture that you'll find strong IDE support for them (e.g., eclipse will make them for you automatically), and if you're working in something that uses the expression language first made for jsps (EL), then you'll be able to use the property notation to access getters and setters.

get* 和 set* 模式虽然在 Java 文化中是如此建立,以至于您会发现对它们的强大 IDE 支持(例如,eclipse 会自动为您制作它们),并且如果您正在使用表达式语言的东西为 jsps (EL) 制作,那么您将能够使用属性符号来访问 getter 和 setter。

回答by Peter Lawrey

I would consider not having the getter or setter as they don't do anything in your case except make the code more complicated. Here is an example without getters or setters.

我会考虑不使用 getter 或 setter,因为除了使代码更复杂之外,它们在您的情况下不会做任何事情。这是一个没有 getter 或 setter 的示例。

class Dummy {
  public String name;
  public Dummy(String name) { this.name = name; }
}

Dummy dummy = new Dummy("fred");
System.out.println(dummy.name);//getter, prints: fred
dummy.name = "lolo";//setter
System.out.println(dummy.name);//getter, prints: lolo

IMHO Don't make things more complicated than you need to. It so often the case that adding complexity will suffer from You-Aint-Gonna-Need-It

恕我直言,不要让事情比你需要的更复杂。通常情况下,增加复杂性会受到You-Aint-Gonna-Need-It 的影响

回答by KingInk

Also before adding setters and getters, it might be a good idea to ask yourself why are you exposing the internal data of the Object in question.
I suggests you read this article - http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

同样在添加 setter 和 getter 之前,问问自己为什么要公开相关对象的内部数据可能是个好主意。
我建议你阅读这篇文章 - http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

回答by Nate Parsons

An IDE-independent way is to use Lombok, an annotation-based library that generates getters, setters, and even equals()and hashcode(). It does this for the compiler, but not in the source file, so you don't have to look at the methods, just use them.

一种独立于 IDE 的方法是使用Lombok,这是一个基于注释的库,可生成 getter、setter 甚至equals()hashcode()。它为编译器执行此操作,但不在源文件中执行此操作,因此您不必查看方法,只需使用它们即可。