How to dynamically redefine superclass functions using generics

If you have a base class that is in a jar file that looks like this:

public class A {

public void awesome(int i){

}

}

... which is distributed by these classes (also in the bank) as follows:

public class A1 extends A {

@Override
public void awesome(int i){

}

}

and

public class A2 extends A {

@Override
public void awesome(int i){

}

}

... is it possible to override the base function in a general way?

Let's say there is an implementation that is added through an anonymous inner class - can you code so that the entire anonymous inner implementation appears only once? Therefore, instead of:

public class Test {

public static void main(String args[]){

    A1 mySpecialA1 = new A1(){
        @Override
        public void awesome(int i){
            //awesome implementation
        }
    };

    A2 mySpecialA2 = new A2(){
        @Override
        public void awesome(int i){
            //awesome implementation
        }
    };
}

}

... you could (where it breaks):

public class SpecialAFactory {

public static <T extends A> getSpecialA(){
    return new T(){
        @Override
        public void awesome(int i){
            //only once
        }
    };
}

}

Thus, in the end, you must pass to the subclass that you want to get a new anonymous instance.

+3
source share
1 answer

, , , :

public class Test {

public static void main(String args[]){

    A1 mySpecialA1 = new A1(){
        @Override
        public void awesome(int i){
            awesomeImplementation(i);
        }
    };

    A2 mySpecialA2 = new A2(){
        @Override
        public void awesome(int i){
            awesomeImplementation(i);
        }
    };
}

private static void awesomeImplementation(int i) {
    //awesome implementation
}

}
+2

All Articles