英文:
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> {
}
...
问题是,我为所有其他调用(myObjB、myListB、myObjC、myListC)创建了一个新的。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<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);
}
}
...
Example of interface:
public interface myObjA
extends JpaRepository<A, Long> {
}
public interface myObjB
extends JpaRepository<B, Long> {
}
...
The thing is I'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 <T, N> void save(JpaRepository<T, N> repo, List<T> list) {
if (null != list && !list.isEmpty()) {
repo.saveAll(list);
}
}
// usage
@Autowired
private MyRepo repository; // MyRepo implements JpaRepository<MyObj, Long>
public void foo(List<MyObj> list) {
save(repository, list);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论