Simulation of Python decorator in Java

Business:
put different tags on the data in the table, such as brand tags, product labels, emotional tags, etc.

tagging logic

log.info("{} Start tagging {}",table,label)
// 
log.info("{} End tagging {}",table,label)

Log information can be shared except for specific tagged logic

if you use Python to operate, you can simply define a decorator as follows

def log(func):
    def wrapper(*args):
        print("{} -- Start tagging {}".format(*args))
        result = func(*args)
        print("{} -- End tagging {}".format(*args))
        return result

    return wrapper

@log
def tagging_A(table,lable):
  -sharp  
  print("do something here")
@log
def tagging_B(table,lable):
  print("do something here")

logs are automatically added when tagging_A or tagging_B is called

but Java doesn"t have a decorator as easy to use as Python, so I decided to use the template mode as follows

    // 
    private void taggingTemplate(String table,String label,Runnable action){
        log.info("{} -- Start tagging {}",table,label);
        action.run(); // 
        log.info("{} -- End tagging {}",table,label);
    }
    
    public void taggingA(){
        taggingTemplate("table_a","label_A",()->{
            // 
            System.out.println("do something here");
        });
    }
    

is there any other lightweight way to simulate Python decorator in Java besides template mode?

Mar.06,2021

AOP get to know

Menu