lundi 14 septembre 2020

Java Generics - How to read fields or invoke method on a type passed to a generic method

Convert a method to generics and is the below use case good enough to convert this to generics or there would be some long term disadvantages

Use Case

  • Firstly, i had one publish api to publish a specific entity,wrote a specific method like publishAccountInfo(AccountInfo accountInfo)

  • But the requirements changed and now UserGeographyInfo and UserBehaviorInfo can also be published.So I had option to write 2 new methods or convert the existing to be generic.

  • Also, earlier in the publishAccountInfo(AccountInfo accountInfo) i was doing some logic like adding additional info from context about user id,username etc which was not part of the AccountInfo object which i would plan to move out to other method if i use Generic Method.

    public PubResponse publishAccountInfo(AccountInfo accountInfo){
      ConfigObj cfg=null;   //this object will have specific api url for publishing
      PubResponse response;
      AccountInfo.setUserName(context.getUser);   //This is specific to AccountInfo object logic and would be moved out.
      //using spring RestTemplate exchange method
     ResponseEntity<HashMap> result = 
             restTemplate.exchange(cfg.getAPIurl(), 
                                   HttpMethod.POST, getHttpEntity(accountInfo), HashMap.class);
     HashMap<String,String> res=result.getBody();
         response=new PubResponse(res.get("statusMsg"),accountInfo.getAccountNum()); //logging some info about what is published and what was the status of publish
    
     return response;
     }
    

If i convert to Generic am having issue at below points

public <T> PubResponse publishAPI(T genericType){
 ConfigObj cfg=null;  //this cannot be generic, is this fine to be inside this generic method?
 PubResponse response;

        ResponseEntity<HashMap> result = 
                restTemplate.exchange(cfg.getAPIurl(), 
                                      HttpMethod.POST, getHttpEntity(genericType), HashMap.class);
        HashMap<String,String> res=result.getBody();
            response=new PubResponse(res.get("statusMsg"),genericType.getAccountNum()); //compiler complains as there is no getAccountNum method in genericType

}

@Data
@AllArgsConstructor
public static class PubResponse{
private final String statusMsg;
private final String someUniqueNum;   //mostly primary key of entity saved to db and published.
}

Spent good time searching for example, but could not get any similar example.Tried to go through java library code as well. Reflection also but could not make sense out of it :(

Aucun commentaire:

Enregistrer un commentaire