如何在Java中将通用对象作为方法参数传递?

huangapple go评论69阅读模式
英文:

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&lt;Dog&gt; getListDogs(SearchResponse response) {

    SearchHit[] searchHit = response.getHits().getHits();

    List&lt;Dog&gt; dogList = new ArrayList&lt;&gt;();

    if (searchHit.length &gt; 0) {

        Arrays.stream(searchHit).forEach(hit -&gt; 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&lt;Generic&gt; 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 &lt;T&gt; List&lt;T&gt; getSearchResult(SearchResponse response , Class&lt;T&gt; clazz) {

    SearchHit[] searchHit = response.getHits().getHits();

    List&lt;T&gt; lisOfObjects = new ArrayList&lt;&gt;();

    if (searchHit.length &gt; 0) {
             Arrays.stream(searchHit).forEach(hit -&gt; lisOfObjects.add(objectMapper.convertValue(hit.getSourceAsMap(),clazz)));
    }

    return lisOfObjects;
}

huangapple
  • 本文由 发表于 2020年10月26日 23:17:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64539913.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定