Notification of any String object construction in

2019-09-09 23:18发布

问题:

  1. Is there a way to get notified on all invocations to constructor of String class (either directly or using reflection) without weaving or instrumenting rt.jar?

  2. Further is it possible to filter these notifications only for calls within a specific package?

  3. Further is it possible to make these notifications async (like events) so that actual JVM invocations are not slowed down

My use-case is to intercept all strings being created, make a pattern match on the content and raise alters based on some rules (all in backend) as part of some platform component.

As I don't want to instrument rt.jar, AspectJ seems to be out of question (as LTW can't be done on java core classes). The potential tool seems to JVM TI, but I am not exactly sure how to achieve it.

Thanks, Harish

回答1:

Is there a way to get notified on all invocations to constructor of String class (either directly or using reflection) without weaving or instrumenting rt.jar in compile time?

You are not compiling the String class, so you can only do weaving at runtime. And yes, this is the only way without creating a custom JVM.

Further is it possible to filter these notifications only for calls within a specific package?

It is possible to check the caller with Reflection.getCallerClass(n)

Further is it possible to make these notifications async (like events) so that actual JVM invocations are not slowed down

All this is very expensive as is passing work to another thread.

make a pattern match on the content

Pattern matching is very expensive compared to creating a String. If you are not careful you will slow down your application by an order of magnitude or two. I suggest you reconsider your real requirements and see if there is another way to some what you are trying to do.

Are you sure you don't want to use a profiler to do this. Note: even profilers generally only sub-sample e.g. every 10th allocation. There is plenty of free ones, in fact two come with the JVM. I suggest using Flight Recorder to track allocations as this has a very low overhead.