spring boot Java泛型如何读取传递给泛型方法的类型上的字段或调用方法
将方法转换为泛型,下面的用例是否足以将其转换为泛型,或者存在一些长期的缺点
用例
首先,我有一个发布api来发布特定的实体,编写了一个特定的方法,如
publishAccountInfo(AccountInfo accountInfo)
但是需求改变了,现在
UserGeographyInfo
和UserBehaviorInfo
也可以发布。因此,我可以选择编写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 楼答案
您可以在} 作为参数,并提取所需的精确值
publish
方法中将^{在我的例子中,PubResponse具有对象类型
或者
直接传递
S
两者都提供了输出: