Can aspectj add methods to java.lang.String

I was just looking for something else and stumbled across this question. I want to point out that Kowser's answer, even though it was accepted, is somewhat incorrect. The question mentions no restriction to LTW, so CTW is still in the race. It is possible to weave the JDK/JRE class files and then prepend the advised classes to the boot class path in a later step. I have done it before (even exactly what was asked, i.e. declaring a new method within String), and it works without problems.


No, you can't do this my friend.

I think this is what you are looking for Type not exposed to user

For further details please take a look at The AspectJ Development Environment Guide #Special Cases

As it says

The following classes are not exposed to the LTW infrastructure regardless of the aop.xml file(s) used

  • All org.aspectj.* classes (and subpackages) - as those are needed by the infrastructure itself
  • All java.* and javax.* classes (and subpackages)
  • All sun.reflect.* classes - as those are JDK specific classes used when reflective calls occurs

I'm by no means an expert on aspectj, but I believe you can do both of these things.

To add methods to a class, or even make it implement a new interface and supply the implementation through an aspect, I think you want inter-type declarations.

AspectJ does its work by byte-code manipulation, so you do not need access to the source of the classes you're altering.

Tags:

Java

Aop

Aspectj