Java: Is it possible to always execute a certain function before other functions are called? (Like @Before in JUnit)

前端 未结 7 1661
情歌与酒
情歌与酒 2021-01-02 23:59

Is there a way to always execute a function before any other function of a class is called?

I have a class where I need to refresh some fields always before any func

7条回答
  •  情书的邮戳
    2021-01-03 00:44

    You can have a protected getter method for data. Access getData method instead of using data field. Child classes will see only getData and will have updated data every time.

    public class Example {
    
        private int data;
    
        public void function1(){
    
        }
    
        public void function2(){
    
        }
    
        protected int getData(){
            refresh();
            return data;
        }
    
        //@BeforeOtherFunction
        private void refresh(){
            // refresh data
        }
    }
    

提交回复
热议问题