简体   繁体   中英

Sharing objects between Java classes without going via a method

I'm looking at a way to add some tracing diagnostics to some legacy Java code. By legacy in this sense I mean I cannot change any of the methods. If we consider the following objects:

public class ClassIOwnAndCanChange {

    public static void main(String[] args) {
        // store my object here that I want to make
        // available in LegacyClassA and B
        myMethod("foo", 100);
    }    

}

public class LegacyClassA {

    // method I cannot change
    public void myMethod(String name, int timer) {

        //want to get my 'injected' object here so that I can, 
        //for instance, time this method
        methodCallThatTakesSomeTime("some param");

    }  

}

public class LegacyClassB {

    // method I cannot change
    public void methodCallThatTakesSomeTime(String name) {
        // want to get my 'injected' object here for
        // diagnostic reasons

    }

}

I own A and I would like to make an object available in B and C. What is the right way to do this in Java without changing the method that A calls on B and the method that B calls on C?

You can play all sorts of games with AOP ( Aspect Oriented Programming ) and/or other forms of bytecode manipulation.

Whether or not you should varies wildly.

It depends on your precise needs, and how you need to use the "injected" object. I'd consider AOP first since tools like AspectJ are mature. AOP and a ThreadLocal might be all you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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