Is it possible to change buggy class in a closed source library that was not built to support dependency injection?

StackOverflow https://stackoverflow.com/questions/22900381

  •  28-06-2023
  •  | 
  •  

문제

Say I am using a closed source java library with a known buggy class, say BuggyClass and this class is hardcoded throughout the rest of the library. So I would imagine that the java library looks something like this:

public class BuggyClass {
    public T buggyMethod (...) {
        // Buggy code here
    }
}

with several other classes in the library that make use of this class:

public class Example {
    private BuggyClass = new BuggyClass(); // No dependency injection possible

    public Example (/* No way to pass in my own subclass of BuggyClass*/) {
        //  ...
    }
}

etc...

Is there any hack, or workaround, possibly using the class loader so that I could subclass BuggyClass and get Example (and every other class in the library that has BuggyClass hardcoded in) to use my subclass?

도움이 되었습니까?

해결책

You can't do a subclass, no, but you can write your own BuggyClass entirely and make sure it appears earlier in the classpath than the real one. I don't think it's documented, but the default classloader seems to typically use the first matching class it finds.

But obviously this is a Really Bad Option, so you want to exhaust every other avenue before trying to solve temporarily work around the underlying problem this way.

Example: Suppose we have this:

// The "buggy" class
package somepackage;

public class BuggyClass {
    public String someMethod() {
        return "I'm in the buggy class";
    }
}

and this:

// Uses the "buggy" class
package somepackage;

public class BuggyClassUser {
    public String useBuggyClass() {
        BuggyClass c = new BuggyClass();
        return c.someMethod();
    }
}

compiled and the classes in buggy.jar. Then we have this test class:

import somepackage.*;

public class Test {
    public static final void main(String[] args) {
        BuggyClassUser u = new BuggyClassUser();
        System.out.println(u.useBuggyClass());
    }
}

If we run that (*nix format classpath):

java -cp .:buggy.jar Test

...we see

I'm in the buggy class

But if we create a somepackage directory and put this in it:

package somepackage;

public class BuggyClass {
    public String someMethod() {
        return "I'm in the fixed class"; // <== Difference here
    }
}

...and compile that, since we have that in our classpath in front of the jar, this command:

java -cp .:buggy.jar Test

...now gives us this:

I'm in the fixed class

Again, this is very, very much a workaround, not a solution.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top