Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can aspectj add methods to java.lang.String

Tags:

java

aop

aspectj

I've read some articles of aspectj, I know it can enhance classes, which is attractive. I've a very stupid question that I can't find a clear answer:

Can aspectj add methods to java.lang.String?

Or similar question: If I can't get the sources of some classes, can I enhance them by aspectj?

like image 727
Freewind Avatar asked Jul 02 '11 15:07

Freewind


3 Answers

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.

like image 195
kriegaex Avatar answered Sep 22 '22 18:09

kriegaex


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
like image 21
Kowser Avatar answered Sep 24 '22 18:09

Kowser


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.

like image 22
Don Roby Avatar answered Sep 24 '22 18:09

Don Roby