将一个方法转换为通用方法,以避免重复的代码。

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

Convert a method to a generic one to avoid duplicate code

问题

我需要帮助处理以下内容:我有多个调用方法看起来像这样:

private void saveA(myObjA myObj, List<A> myList) {
    if (myList != null && !myList.isEmpty()) {
        myObj.saveAll(myList);
    }
}

private void saveB(myObjB myObj, List<B> myList) {
    if (myList != null && !myList.isEmpty()) {
        myObj.saveAll(myList);
    }
}

...

接口示例

public interface myObjA
    extends JpaRepository<A, Long> {

}

public interface myObjB
    extends JpaRepository<B, Long> {

}

...

问题是我为所有其他调用myObjBmyListBmyObjCmyListC创建了一个新的myObj实际上是一个接口第二个参数总是一些对象的列表有没有办法将这个方法转换为一个单一的方法并在调用中指定对象类型


<details>
<summary>英文:</summary>

I need some help with the following: I have multiple calls to a method that look like this:

    private void saveA(myObjA myObj, List&lt;A&gt; myList) {
        if (myList != null &amp;&amp; !myList.isEmpty()) {
            myObj.saveAll(myList);
        }
    }

    private void saveB(myObjB myObj, List&lt;B&gt; myList) {
        if (myList != null &amp;&amp; !myList.isEmpty()) {
            myObj.saveAll(myList);
        }
    }

    ...

Example of interface:

    public interface myObjA
        extends JpaRepository&lt;A, Long&gt; {

    }

    public interface myObjB
        extends JpaRepository&lt;B, Long&gt; {

    }

    ...

The thing is I&#39;m creating a new one for all the other calls (myObjB, myListB, myObjC, myListC). myObj is actually an interface and the second parameter is always a list of some object. Is there any way to convert this method to a single one and specify the object type in the call?

</details>


# 答案1
**得分**: 5

可以使用通用方法来完成这个操作
```java
public <T, N> void save(JpaRepository<T, N> repo, List<T> list) {
    if (null != list && !list.isEmpty()) {
        repo.saveAll(list);
    }
}

// 使用示例
@Autowired
private MyRepo repository;  // MyRepo实现了JpaRepository<MyObj, Long>

public void foo(List<MyObj> list) {
    save(repository, list);
}
英文:

This can be done using generic method:

public &lt;T, N&gt; void save(JpaRepository&lt;T, N&gt; repo, List&lt;T&gt; list) {
    if (null != list &amp;&amp; !list.isEmpty()) {
        repo.saveAll(list);
    }
}

// usage
@Autowired
private MyRepo repository;  // MyRepo implements JpaRepository&lt;MyObj, Long&gt;

public void foo(List&lt;MyObj&gt; list) {
    save(repository, list);
}

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

发表评论

匿名网友

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

确定