[英]How can I intercept a method call to a library class in Java or Android?
I have a library class that is a singleton and does NOT implement any interface (So I'm assuming I cannot use dynamic proxies). 我有一个单例且没有实现任何接口的库类(因此,我假设我不能使用动态代理)。 But, I need the same functionality as the dynamic proxy.
但是,我需要与动态代理相同的功能。 I need to hijack the call, log some data and pass on the call to the library as is.
我需要劫持该调用,记录一些数据并将调用直接传递给库。
Is it possible to do this without having to use AspectJ or Spring AOP? 是否可以不必使用AspectJ或Spring AOP来做到这一点? (I'm not sure how to use these frameworks, but I will have to look into it if there is no other way).
(我不确定如何使用这些框架,但是如果没有其他方法,我将不得不对其进行研究)。
You can provide your own implementation of the same class, with the same name and package, and try to put it into classpath first. 您可以提供具有相同名称和包的相同类的自己的实现,并尝试首先将其放入类路径中。 The calling code with such classpath will pick the intercepting class first, and the intercepting class can call others classes of the actual package to provide its actual functionality.
具有此类类路径的调用代码将首先选择拦截类,并且拦截类可以调用实际包的其他类以提供其实际功能。
Best would be to remove the overridden class from the library .jar with archive tool. 最好是使用存档工具从库.jar中删除覆盖的类。
You could change the import statements in the classes that call f() so that they see a different class that implements f(). 您可以在调用f()的类中更改import语句,以便它们看到实现f()的其他类。 The implementation of that class would do the logging and call the real f().
这个类的实现会做记录和调用真实F()。
Still requires some editing, but less than changing every call. 仍然需要进行一些编辑,但不必更改每个呼叫。
BTW: Depending on the size of the project, you may want to consider making wrappers to that "black box" anyway, if this type of requirement will be ongoing. 顺便说一句:如果这种要求仍在进行,则取决于项目的规模,您可能仍要考虑对该“黑匣子”进行包装。
Like I started in my comment wrapper all the classes you implement from the external library. 就像我在注释包装器中开始的那样,您是从外部库实现的所有类。 Then call the external library from your own classes this way you can log in the function(s) you want.
然后以这种方式从您自己的类中调用外部库,即可登录所需的函数。 If you use the same function name then you don't have to change what you call you only have to change your import(s).
如果使用相同的函数名称,则不必更改调用的名称,而只需更改导入。 Most IDEs provide mass name replace so it shouldn't be too big of a burden it will be tedious however.
大多数IDE提供批量名称替换,因此它不会带来太大的负担,但是会很乏味。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.