简体   繁体   English

Java:在现有静态方法的过程中附加一个附件

[英]Java: Annexing an Addition to the Process of a Preexisting Static Method

I'm working with pre-existing classes, and I am not permitted to alter any of them. 我正在使用预先存在的课程,并且不允许更改其中任何一个。 I am working within the same package as the classes, and am trying to implement new functionality. 我正在与类一起使用同一包,并且正在尝试实现新功能。 In one of the classes, there is a static void step() , which is called every time a significant action is completed. 在其中一个类中,有一个static void step() ,每次完成重要操作时都会调用该static void step() This method renders the view, and then calls Thread.sleep() for varying amounts of time. 此方法呈现视图,然后在不同的时间内调用Thread.sleep() Part of the functionality I need to implement needs to be called every time a significant action is completed, before the view renders. 每次重要操作完成时,都需要视图呈现之前调用我需要实现的部分功能。 This means that I need a way to execute code every time step is called, before anything else in step is allowed to execute. 这意味着我需要一种在每次调用step之前都执行代码的方法,然后才允许执行该step任何其他操作。

I can't modify step , since it's in a class I can't touch, and I can't extend its enclosing class, since it's a static method, and so every call to it in those untouchable classes is a class-method call, rather than an object reference. 我无法修改step ,因为它在一个我无法触摸的类中,并且我无法扩展其封闭的类,因为它是一个静态方法,因此在那些不可触摸的类中对其的每次调用都是一个类方法调用,而不是对象引用。 That means that even if and when I override the method, it won't be called by any of the other classes. 这意味着即使当我重写该方法时,其他任何类也不会调用该方法。 The way I see it, I have two options: Find a way to automatically insert a modified method into the class whenever it is loaded, or find a way to insert a separate method into the process whenever step is called. 我看到的方式有两个选择:找到一种方法,该方法在每次加载类时将已修改的方法自动插入到类中,或者找到一种在调用step时将单独的方法插入到流程中的方法。 My research has been fruitless in both veins. 我的研究在两方面都是徒劳的。

EDIT 1: As I've come to learn, there are extensions to complete these tasks. 编辑1:随着我的学习,有扩展来完成这些任务。 However, any solutions I use have to stay within the standard JDK. 但是,我使用的任何解决方案都必须保留在标准JDK中。

Look at AspectJ static method weaving. 看一下AspectJ静态方法的编织。 It should allow you to modify your "un-modifiable" class byte code in order to add custom logic to "step()" methods before and after calls. 它应该允许您修改“不可修改的”类字节码,以便在调用之前和之后将自定义逻辑添加到“ step()”方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM