Java – passing methods as parameters – is this possible?
I tried to migrate to Java 8 and have some methods in my Dao class to do the following
@Override @SuppressWarnings("unchecked") public List<Group> getGroups() { Session session = sessionFactory.openSession(); List<Group> allGroups = (List<Group>)session.createQuery("from Group").list(); session.close(); return allGroups; }
Here, the same boiler board sessionfactory is reused for all methods Open and session close.
Is it possible to have an open and close method in Java 8 and use the rest of my code to perform its functions?
If so – what is the name of the process, or anyone can provide some help on how to do this
Solution
Because you want to express a code that works on the session instance (so you can abstract its creation and cleaning), and you can return an arbitrary result, a function < session, t > will be the correct type to encapsulate such code:
public <T> T doWithSession(Function<Session,T> f) { Session session = sessionFactory.openSession(); try { return f.apply(session); } finally { session.close(); } }
Then you can use it:
@Override @SuppressWarnings("unchecked") public List<Group> getGroups() { return doWithSession(session -> (List<Group>)session.createQuery("from Group").list()); }
This is not a special Java 8 technology You can do the same in earlier Java versions. See also what is the "execute around" idiom More easily, Java 8 provides you with an existing function interface, which you can implement using lambda expression instead of using anonymous inner classes or similar inner classes
If the operation you need consists of a single method call and does not require type conversion, you can implement it as a method reference similar to dowithsession (Session:: methodname). See method references in the tutorial