How do I change part of a parent class's constructor when inheriting from it?

86 views Asked by At

I've got some class and I want to make an object out of it. However, this class has a property set in its constructor that makes it unusable for me. I cannot edit this class's code as it exists in a very tight codebase. This property cannot be changed after the object is constructed, so even if there WERE a setter method, it wouldn't work (it's part of the SWT gui framework, and can't be changed dynamically).

My instinct tells me to subclass it and change what I need to change. Should only take a few lines because every other aspect of this class will stay the same. However, since the first line you need to call in a child class's constructor is the super method, that means the parent class's constructor is called before I can even do anything.

Is there ANY way I can make an object out of this class with just ONE small property changed, without having to create an entire new class that's a copy/paste of all its code, except for one small change in like 8?

Thanks!

EDIT: since someone requested code:

public class Parent {
    private Object important_object = null;
    public Parent() {
        important_object = new Object();
        important_object.important_property = BAD;
    }
}

public class Child extends Parent {
    public Child() {
           // how the heck do I make an instance of this
           // class that has important_property set to GOOD
           // instead of BAD?
    }
}
2

There are 2 answers

0
Turing85 On BEST ANSWER

If the attribute is private, no setter to either important_object or important_property is provided and you cannot use Reflection then there is no way to change the attribute.

3
Acapulco On

There is something called classworking, that allows you to modify the Java bytecode in runtime, but it's definitely non-trivial and it probably is way too much for this. Although it's a very interesting read.

http://www.ibm.com/developerworks/library/j-cwt02076/

https://commons.apache.org/proper/commons-bcel/