Java wrapper: overriding a method called in a super constructor

I want to wrap a class in Java, but the problem is this:

public class A {

    public A() {
       doSomething();
    }

    public void doSomething() {
    }

}

Now when I try to wrap this class and delegate all methods to the shell

public class Wrapper extends A {

   private final A a;

   public Wrapper(A a) {
      super();
      this.a = a;
   }

   @Override
   public void doSomething() {
      this.a.doSomeThing();
   }


}

of course, I get NPE because "a" is still null because it is set after a super () call that calls the overriden doSomething () method. Is there a solution to this problem? The only thing that occurred to me was to make a factory method and set a static variable containing a reference to a, but that seems ugly to me.

+4
source share
4 answers

, init ( ) ( ). init:

public class A {

    public A() {
    }

    public void init() {
        doSomething();
    }

    public void doSomething() {
    }
}

, init , :

A instance = new Wrapper();
instance.init();

A instance = new Wrapper();

Spring DI, init-method xml, Spring , .

doSomething , init , Spring.

, - - , . , , , .

0

, doSomething .

, A Wrapper A

public interface IA {

    public void doSomething() {
    }

}
public class A implements IA {

    public A() {
       doSomething();
    }

    public void doSomething() {
    }

}


public class Wrapper implements IA {

   private final IA a;

   public Wrapper(IA a) {
      this.a = a;
      doSomething();
   }

   @Override
   public void doSomething() {
      a.doSomeThing();
   }
}
+1

Wrapper . A. super :

class Wrapper extends A {

    public Wrapper() {
    }

    @Override public void doSomething() {
        super.doSomething();
    }
}

:

class Wrapper implements AA {

    private final AA child;

    public Wrapper(AA child) {
        this.child = child;
    }

    @Override public void doSomething() {
        child.doSomething();
    }
}

class A implements AA {

    public A() {
       doSomething();
    }

    @Override public void doSomething() {}
}

interface AA {
    public void doSomething();
}
+1

, ,

 public class Wrapper extends A {

       private final A a;

       public Wrapper(A a) {
          super();
          this.a = a;

        //this will execute method doSomething wrom Wrapper class after variable a is set
          doSomething(); 

       }

       @Override
       public void doSomething() {
    //this will prevent to call metod from superclass constructor, bit risky thou
         if (a!=null)       
          this.a.doSomething();
       }
    }

, , .

0

Source: https://habr.com/ru/post/1535898/


All Articles