简体   繁体   中英

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. Is there any good reason to directly reference the Object class?

API calls/responses (consuming/producing JSON) will always have a String key but the value may be text, numeric, boolean, array, or an object.

In the specific case of my project we use Spring MVC (which uses Jackson under the hood). Our controllers always consume domain objects directly, eg an instance of the User class. Processing a Map with more than a couple of keys is a chore and prone to error.

We frequently return Map<String, Object> because responses almost always include metadata that is generated when the request is made. For example, a GET request made to myapp/api/users might return something like:

{
  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. There is no point to creating a UsersResponseEntity class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM