Java 中类似于 JavaScript 的 Object 数据类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26785759/
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-10-28 06:29:14  来源:igfitidea点击:

JavaScript-like Object data type in Java?

javajavascriptjsonobjecttypes

提问by Anon

I am experienced in JavaScript, but new to Java. In JavaScript there are "object" data types where a given variable essentially has sub-variables with their own unique values, for example:

我在 JavaScript 方面很有经验,但对 Java 不熟悉。在 JavaScript 中有“对象”数据类型,其中给定的变量本质上具有具有自己唯一值的子变量,例如:

var car = {type:"Fiat", model:500, color:"white"};

It is almost like an array, but not quite (JavaScript has arrays too). I am wondering if the same type of thing exists in Java? If so, how would I declare the same thing in Java? Based on my searches I can't find an object data type, but thought maybe there was something similar?

它几乎像一个数组,但又不完全是(JavaScript 也有数组)。我想知道 Java 中是否存在相同类型的东西?如果是这样,我将如何在 Java 中声明相同的内容?根据我的搜索,我找不到对象数据类型,但认为可能有类似的东西?

回答by ssube

While Java has a type called object, it's not what you want. Almost everything in Java is an object, and there are two ways to handle this:

虽然 Java 有一个名为 的类型object,但它不是您想要的。Java 中几乎所有东西都是对象,有两种处理方法:

  1. Define a strongly-typed object with the correct properties, as a class. Javascript has a similar concept, implemented differently, but it should be recognizable:

    public class Car {
        private String type;
        private int model;
        private String color;
    
        public Car(final String type, final int model, final String color) {
            this.type = type;
            this.model = model;
            this.color = color;
        }
    
        public String getType() { return this.type; }
        public int getModel() { return this.model; }
        public String getColor() { return this.color; }
    }
    
    final Car car = new Car("Fiat", 500, "white");
    
    // To get the color, you must:
    car.getColor();
    

    Add methods to get and set attributes as appropriate, methods to start, stop, drive, etc.

  2. If you want a loose collection of properties without behavior or restriction, use a Map. Again, there exists a Javascript equivalent (the {x: 1, y: 2}construct withoutusing the newkeyword).

    final Map<String, Object> car = new HashMap<>();
    car.put("type", "Fiat");
    car.put("model", 500);
    car.put("color", "white");
    
    // To get the color, you:
    car.get("color");
    

    The disadvantage with this approach is that the compiler cannot enforce the types of those objects (nearly as well), and the map cannot have custom behaviors (in any reasonable way). In your example, modelwas a number, but this will allow you to assign anything regardless of whether it makes sense (perhaps someone keeps the data on a server and uses an HttpConnection, all of your code expecting a number explodes).

  1. 将具有正确属性的强类型对象定义为类。Javascript 有一个类似的概念,实现方式不同,但它应该是可识别的:

    public class Car {
        private String type;
        private int model;
        private String color;
    
        public Car(final String type, final int model, final String color) {
            this.type = type;
            this.model = model;
            this.color = color;
        }
    
        public String getType() { return this.type; }
        public int getModel() { return this.model; }
        public String getColor() { return this.color; }
    }
    
    final Car car = new Car("Fiat", 500, "white");
    
    // To get the color, you must:
    car.getColor();
    

    根据需要添加获取和设置属性的方法,以及启动、停止、驱动等的方法。

  2. 如果您想要一个没有行为或限制的松散属性集合,请使用Map. 同样,存在一个 Javascript 等效项(使用关键字的{x: 1, y: 2}构造)。new

    final Map<String, Object> car = new HashMap<>();
    car.put("type", "Fiat");
    car.put("model", 500);
    car.put("color", "white");
    
    // To get the color, you:
    car.get("color");
    

    这种方法的缺点是编译器不能强制执行这些对象的类型(几乎也是如此),并且映射不能具有自定义行为(以任何合理的方式)。在您的示例中,model是一个数字,但这将允许您分配任何内容,而不管它是否有意义(也许有人将数据保存在服务器上并使用HttpConnection,您所有期待数字的代码都会爆炸)。

In Java, the first method is recommended if you know you'll have multiple cars, all with the same (or similar) properties. It allows the compiler to both enforce and optimize for the properties that you know will exist, and inheritance allows you to add additional properties later. The class also allow you to define methods which operate on that instance, which can help create abstraction between parts of the system (you don't need to know howa car starts, you just tell the car to start itself).

在 Java 中,如果您知道将拥有多辆汽车,所有汽车都具有相同(或相似)的属性,则建议使用第一种方法。它允许编译器为您知道将存在的属性强制执行和优化,并且继承允许您稍后添加其他属性。该类还允许您定义对该实例进行操作的方法,这有助于在系统各部分之间创建抽象(您不需要知道汽车如何启动,您只需告诉汽车自己启动)。

For reference, the Javascript equivalents are:

作为参考,Javascript 等效项是:

// #1
var Car = function(type, model, color) {
    this.type = type;
    this.model = model;
    this.color = color;
}

var car = new Car("Fiat", 500, "white");

// #2
var car = {type: "Fiat", model: 500, color: "white"};

// For either option, to get the color you can simply:
console.log(car.color);

What should stand out most obviously is that Java keeps track of what type each variable is. Not visible is that Java will prevent you from assigning to unknown properties, say car.mileage, where Javascript will happily add a new property. Finally, Java has a concept of visibility, and makes things private (invisible to outside viewers) by default. Replicating that in Javascript would look something like:

最明显的应该是 Java 会跟踪每个变量的类型。不可见的是,Java 会阻止您分配未知属性,例如car.mileage,Javascript 会很乐意添加新属性。最后,Java 有一个可见性概念,默认情况下将事物设为私有(对外部查看者不可见)。在 Javascript 中复制它看起来像:

var Car = function(type, model, color) {
    var _type = type;
    var _model = model;
    var _color = color;

    this.getType = function() { return _type; }
    this.getModel = function() { return _model; }
    this.getColor = function() { return _color; }
}

console.log(car.getColor());

In Javascript, you take advantage of closure to hide data. Java defaults to hidden, and requires you to expose data when you need to. It's an interesting choice, very relevant when comparing code-bases, and can help keep classes independent of one another. It's also very easy (and tempting) to violate when you start writing in OO languages, so something to keep in mind (using simple structs willcome back to haunt you).

在 Javascript 中,您可以利用闭包来隐藏数据。Java 默认为隐藏,并要求您在需要时公开数据。这是一个有趣的选择,在比较代码库时非常重要,并且可以帮助保持类彼此独立。当您开始使用 OO 语言编写时,也很容易(并且很容易)违反它,所以要记住一些事情(使用简单的结构再次困扰您)。

回答by Ross Drew

Yes, they are called Objects and defined by Classes. It's basically the first thing you learn when learning Java

是的,它们被称为对象并由类定义。这基本上是你在学习 Java 时学到的第一件事

//The definition of an object and it's members
public class Car { 
 String type, model, color;
}

You can then make them public to access and change them external to the class

然后,您可以将它们设为公开,以便在班级外部访问和更改它们

public class Car {
 public String type, model, color;
}

And access them like so

并像这样访问它们

//Create an instance of a Car, point to it with variable c and set one of it's properties/members
 Car c = new Car();
 c.type = "Fiesta";

But allowing variables of a class to be edited externally is considered bad form in Java, generally you would add methods to access each, called accessors

但是允许在外部编辑类的变量在 Java 中被认为是不好的形式,通常你会添加方法来访问每个,称为访问器

public class Car {
  private String type, model, color;

//Return the type of this object
  public String getType(){
    return type;
  }

//Set the type of this object
  public void setType(String type){
    this.type = type;
  }

  //etc
}

Then access them like so

然后像这样访问它们

 Car c = new Car();
 c.setType("Fiesta");

A class is the template you write to create objects, which are run time instances of classes.

类是您为创建对象而编写的模板,这些对象是类的运行时实例。

回答by degr

Most nice object for this purpose it's a LinkedHashMap. You can use it like map, but on iteration it will keep keys order.

为此目的,最好的对象是LinkedHashMap。你可以像 map 一样使用它,但在迭代时它会保持键的顺序。