Schokokuchen Bäcker Schokokuchen Bäcker - 3 months ago 11
Java Question

Is it possible to acces this.getClass() before calling super()

I want to call

this.getClass()
before calling the constructor with
super(...)
.

abstract class A extends SuperClass {
public A() {
super(Manager.someOtherMethod(this.getClass()))
// Does not work: "Cannot reference 'Object.getClass()' before
// supertype constructor has been called".
}
}


I read about a workaround using static methods, but
this.getClass()
cannot be called from a static context.


This question depends on my previous question.


Thanks in advance for you answers :)

Answer

I suggest you to refactor your code.

I assume that you have classes A1, A2 and A3 now.

You should introduce factory like this:

class AFactory {
    public static A1 newA1() {return new A1(A1.class);}
    public static A2 newA2() {return new A2(A2.class);}
    public static A3 newA3() {return new A3(A3.class);}
}

Add parameter to classes A1, A2 and A3 constructors.

Add parameter to A constructor.