Can aspectj add methods to java.lang.String

2019-06-18 23:46发布

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?

标签: java aspectj
3条回答
女痞
2楼-- · 2019-06-18 23:59

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
查看更多
The star\"
3楼-- · 2019-06-18 23:59

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.

查看更多
我命由我不由天
4楼-- · 2019-06-19 00:08

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.

查看更多
登录 后发表回答