Search code examples
aopaspectj

Add toString method to class using AspectJ


I have a class which I can't modify but I want to change the behaviour of one of it's methods.

public class TestClass {
}

I would like to pointcut the toString method inside of it so instead of returning "TestClass@a8d8as" it will return "hello".

@Around("execution(* *(..)) && this(com.test.TestClass)")

This works If I define the toString method inside TestClass, but won't work with the implicit one.

I haven't worked with aspects for a long time and I'm quite new at them, is there something I'm missing or a way to do what I want?

Thanks!


Solution

  • You asked for an AspectJ solution despite having solved the problem via Javassist. So here it is according to Nándor's suggestion:

    package de.scrum_master.app;
    
    public class TestClass {
      private String tableName;
    
      public TestClass(String tableName) {
        this.tableName = tableName;
      }
    
      public static void main(String[] args) {
        System.out.println(new TestClass("Invoice"));
        System.out.println(new TestClass("InvoiceItem"));
      }
    }
    
    package de.scrum_master.aspect;
    
    import de.scrum_master.app.TestClass;
    
    public privileged aspect ToStringAspect {
      public String TestClass.toString() {
        return tableName;
      }
    }
    

    Console log:

    Invoice
    InvoiceItem