Java Pass Method as Parameter

后端 未结 16 1003
滥情空心
滥情空心 2020-11-22 02:17

I am looking for a way to pass a method by reference. I understand that Java does not pass methods as parameters, however, I would like to get an alternative.

I\'ve

16条回答
  •  温柔的废话
    2020-11-22 02:50

    I did not found any solution here that show how to pass method with parameters bound to it as a parameter of a method. Bellow is example of how you can pass a method with parameter values already bound to it.

    1. Step 1: Create two interfaces one with return type, another without. Java has similar interfaces but they are of little practical use because they do not support Exception throwing.
    
    
        public interface Do {
        void run() throws Exception;
        }
    
    
        public interface Return {
            R run() throws Exception;
        }
    
    
    1. Example of how we use both interfaces to wrap method call in transaction. Note that we pass method with actual parameters.
    
    
        //example - when passed method does not return any value
        public void tx(final Do func) throws Exception {
            connectionScope.beginTransaction();
            try {
                func.run();
                connectionScope.commit();
            } catch (Exception e) {
                connectionScope.rollback();
                throw e;
            } finally {
                connectionScope.close();
            }
        }
    
        //Invoke code above by 
        tx(() -> api.delete(6));
    
    

    Another example shows how to pass a method that actually returns something

    
    
            public  R tx(final Return func) throws Exception {
        R r=null;
        connectionScope.beginTransaction();
        try {
                    r=func.run();
                    connectionScope.commit();
                } catch (Exception e) {
                    connectionScope.rollback();
                    throw e;
                } finally {
                    connectionScope.close();
                }
            return r;
            }
            //Invoke code above by 
            Object x= tx(() -> api.get(id));
    
    

提交回复
热议问题