简体   繁体   中英

Retrieve object fields described in field list

I'm have list with fields to retrieve from basic object. I tried to use a map but it did not work. For example: I have below base object "Audit" (as a json, to better describe)

{
    "sendDate": "11/11/2017",
    "id": "1",
    "user": "name1",
    "role": "admin",    
    "auditType": "download",
    "points": 3
}

And I get from different microservices a list with fields to return, for example

["sendDate", "id", "auditType"] 

and for this example I should return below "Audit" :

{
    "sendDate": "11/11/2017",
    "id": "1",  
    "auditType": "download"
}

and I have to return Audit type with only fields described in fields list. Is there any smart solution? I know i may use a lot of if but the real case is much more complex so I'm currently looking for a smart solution and cannot find any one. Thank you

Assuming you have a java class with fields named like the keys in your json example and you want to create a new object form a source object where only the selected fields are set, you can use something like this:

@SuppressWarnings("unchecked")
public <T> T getObjectWithSelectedFields(T sourceObject, Collection<String> fields)
    throws InstantiationException, IllegalAccessException {
  Class<?> clazz = sourceObject.getClass();
  Object targetObject = clazz.newInstance();

  Arrays.stream(clazz.getDeclaredFields()).filter(f -> fields.contains(f.getName())).forEach(f -> {
    try {
      f.set(targetObject, f.get(sourceObject));
    } catch (IllegalArgumentException | IllegalAccessException e) {
      // TODO ...
    }
  });

  return (T)targetObject;
 }

You can easily implement a similar approach using getters and setters.

Please not that however this will create a new object of the same type as the source object ("Audit" I guess). The difference will be that only the fields provided in your fields list will be set - all others will be null . What you cannot do is to dynamically create a new class that'll only contain the fields that you requested. In this case I'd rather go for collecting selecting values to a map.

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