有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

spring boot Java泛型如何读取传递给泛型方法的类型上的字段或调用方法

将方法转换为泛型,下面的用例是否足以将其转换为泛型,或者存在一些长期的缺点

用例

  • 首先,我有一个发布api来发布特定的实体,编写了一个特定的方法,如publishAccountInfo(AccountInfo accountInfo)

  • 但是需求改变了,现在UserGeographyInfoUserBehaviorInfo也可以发布。因此,我可以选择编写2个新方法或将现有方法转换为泛型方法

  • 另外,在前面的publishAccountInfo(AccountInfo accountInfo)中,我做了一些逻辑工作,比如从上下文中添加关于用户id、用户名等的附加信息,这些信息不是AccountInfo对象的一部分,如果我使用泛型方法,我计划将其移到其他方法

    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;
     }
    

如果我转换为通用,我在以下几点有问题

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 :(


共 (1) 个答案

  1. # 1 楼答案

    您可以在publish方法中将^{}作为参数,并提取所需的精确值

    在我的例子中,PubResponse具有对象类型

    public class GenericsExample {
    
        @Data
        @AllArgsConstructor
        static class AccInfo {
            String accNo;
        }
    
        @Data
        @AllArgsConstructor
        static class PersonalInfo {
            int perId;
        }
    
        @Data
        @AllArgsConstructor
        static class PubRes {
            String msg;
            Object object;
        }
    
        public static <T, S> PubRes publish(T t, Supplier<S> supplier) throws Exception {
            // Do your action here.
            return new PubRes("msg", supplier.get());
        }
    
        public static void main(String[] args) throws Exception{
            ObjectMapper objectMapper = new ObjectMapper();
            AccInfo accInfo = new AccInfo("accountinfo");
            PersonalInfo personalInfo = new PersonalInfo(1);
    
            PubRes pubRes;
            // Passing accNo for AccInfo
            pubRes = publish(accInfo, () -> accInfo.getAccNo());
            System.out.println(objectMapper.writeValueAsString(pubRes));
    
            // Passing perId for PersonalInfo
            pubRes = publish(personalInfo, () -> personalInfo.getPerId());
            System.out.println(objectMapper.writeValueAsString(pubRes));
        }
    }
    

    或者

    直接传递S

    public static <T, S> PubRes publish(T t, S s) throws Exception {
        System.out.println(new ObjectMapper().writeValueAsString(t));
        return new PubRes("msg", s);
    }
    
    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        AccInfo accInfo = new AccInfo("accountinfo");
        PersonalInfo personalInfo = new PersonalInfo(1);
    
        PubRes pubRes;
        pubRes = publish(accInfo, accInfo.getAccNo());
        System.out.println(objectMapper.writeValueAsString(pubRes));
    
        pubRes = publish(personalInfo, personalInfo.getPerId());
        System.out.println(objectMapper.writeValueAsString(pubRes));
    }
    

    两者都提供了输出:

    {"msg":"msg","object":"accountinfo"}
    {"msg":"msg","object":1}