英文:
How to pass generic pbject as method parameter in Java?
问题
我正在进行一个Java项目,我想传递一个Java对象给一个方法,以避免代码重复。这是我的代码:
private List<Dog> getListDogs(SearchResponse response) {
SearchHit[] searchHit = response.getHits().getHits();
List<Dog> dogList = new ArrayList<>();
if (searchHit.length > 0) {
Arrays.stream(searchHit).forEach(hit -> dogList.add(objectMapper.convertValue(hit.getSourceAsMap(), Dog.class)));
}
return dogList;
}
我有其他需要使用相同方法的对象,比如猫对象和马对象。你有任何关于如何使我的方法通用化的想法,以便只需将对象类型作为参数传递吗?
类似这样:
private <T> List<T> getListObject(SearchResponse response, Class<T> objectType) {...
英文:
I'm working on a Java project, and I want to pass a Java object to a method in order to avoid code duplication. This is my code :
private List<Dog> getListDogs(SearchResponse response) {
SearchHit[] searchHit = response.getHits().getHits();
List<Dog> dogList = new ArrayList<>();
if (searchHit.length > 0) {
Arrays.stream(searchHit).forEach(hit -> dogList.add(objectMapper.convertValue(hit.getSourceAsMap(),Dog.class))
);
}
return dogList;
}
I have other objects that need to use the same method like Cat Object and Horse object. Do you have any idea on how I can make my method generic in order to pass just the object type as a parameter?
Something like this:
private List<Generic> getListObject(SearchResponse response , GenericObject object){...
答案1
得分: 0
根据上面的评论,我发现了解决我的问题的方法,以下是通用的方法代码:
private <T> List<T> getSearchResult(SearchResponse response, Class<T> clazz) {
SearchHit[] searchHit = response.getHits().getHits();
List<T> lisOfObjects = new ArrayList<>();
if (searchHit.length > 0) {
Arrays.stream(searchHit).forEach(hit -> lisOfObjects.add(objectMapper.convertValue(hit.getSourceAsMap(), clazz)));
}
return lisOfObjects;
}
英文:
Following the comments above, I found out how to resolve my problem, and this is the generic method code:
private <T> List<T> getSearchResult(SearchResponse response , Class<T> clazz) {
SearchHit[] searchHit = response.getHits().getHits();
List<T> lisOfObjects = new ArrayList<>();
if (searchHit.length > 0) {
Arrays.stream(searchHit).forEach(hit -> lisOfObjects.add(objectMapper.convertValue(hit.getSourceAsMap(),clazz)));
}
return lisOfObjects;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论