Convert a method to a generic one to avoid duplicate code

Viewed 90

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?

1 Answers

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);
}
Related