[英]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.