java - Passing method as a parameter - Is this possible? -


i trying migrate java 8 , have number of methods in dao classes 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 same boiler plate sessionfactory.open , session.close repeated methods.

is possible in java 8 have method open , close , takes function rest of code , execute inbetween?

if - name of process , or can provide on how might achieved

since want express code works on session instance (so can abstract creation , cleanup of it) , might return arbitrary result, function<session,t> right type encapsulating such code:

public <t> t dowithsession(function<session,t> f) {     session session = sessionfactory.opensession();     try {         return f.apply(session);     }     {         session.close();     } } 

then can use like:

@override @suppresswarnings("unchecked") public list<group> getgroups() {     return dowithsession(session -> (list<group>)session.createquery("from group").list()); } 

this isn’t special java 8 technique. can same in earlier java version, see what “execute around” idiom (thanks gustafc link). makes easier java 8 provides existing function interface , can implement interface using lambda expression instead of having resort anonymous inner classes or such alike.

if desired operation consists of single method invocation , doesn’t require type cast, can implement method reference dowithsession(session::methodname), see method references in tutorial


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -