简体   繁体   English

应该在 Java 中引用 Object 类吗?

[英]Should the Object class ever be referenced in Java?

I found this part of code:我找到了这部分代码:

Map<String, Object> myMap = ...

It seems like the above should replace Object with some abstract class or interface that provides more structure for the value in the map.上面似乎应该用一些抽象类或接口替换Object ,为地图中的值提供更多结构。 Is there any good reason to directly reference the Object class?有什么好的理由直接引用Object类吗?

API calls/responses (consuming/producing JSON) will always have a String key but the value may be text, numeric, boolean, array, or an object. API 调用/响应(使用/生成 JSON)将始终具有String键,但值可以是文本、数字、布尔值、数组或对象。

In the specific case of my project we use Spring MVC (which uses Jackson under the hood).在我的项目的特定情况下,我们使用 Spring MVC(在幕后使用 Jackson)。 Our controllers always consume domain objects directly, eg an instance of the User class.我们的控制器总是直接使用域对象,例如User类的实例。 Processing a Map with more than a couple of keys is a chore and prone to error.处理具有多个键的Map是一件苦差事并且容易出错。

We frequently return Map<String, Object> because responses almost always include metadata that is generated when the request is made.我们经常返回Map<String, Object>因为响应几乎总是包含在发出请求时生成的元数据。 For example, a GET request made to myapp/api/users might return something like:例如,对myapp/api/users发出的 GET 请求可能会返回如下内容:

{
  count: 2,
  timestamp: '2020-11-06T17:24:12.123Z',
  users: [
    {id: 1, firstName: 'Alice', lastName: 'Ackbar'},
    {id: 2, firstName: 'Boba', lastName: 'Bling'}
  ]
}

While the users property contains serialized User entities the remaining fields exist solely for the response.虽然users属性包含序列化的User实体,但其余字段仅用于响应。 There is no point to creating a UsersResponseEntity class.创建UsersResponseEntity类毫无意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我是否应该在Service类上使用@Transactional - Should I ever use @Transactional on a Service class 父类是否应该引用子类? - Should a parent class ever reference child classes? 2个不同类的Java对象是否应该相等? - Should 2 Java objects of different classes ever be equal? Java GC:在只扩展Object的类中调用super.finalize()是否有意义? - Java GC: does it ever make sense to call super.finalize() in a class that only extends Object? null引用的Singleton类对象 - Singleton class object referenced by null java class:“引用到newMethodName的类名” - java class :“ classname referenced to newMethodName ” 在创建将在多个级别频繁引用的java对象时,使用类实例或使类静态更好吗? - When creating a java object that will be referenced frequently at many levels, is it better to use a class instance or make the class static? 在java中需要克隆对象的原因是什么? - What is the reason for ever needing to clone an object in java? 是否真的有必要使用“监视器”对象(java) - Is it ever truly necessary to use a “monitor” object (java) 无法解析 java.lang.Object 类型,它本质上是从需要的 .class 文件中引用的 - The type java.lang.Object cannot be resolved, it is inherently referenced from reuired .class files
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM