Jiahui Zhou
Jiahui Zhou

Reputation: 9

How can I create instance in Java when the factory method is default(non-static)

class X {                         
    private int i;           
    private X(){}             
    X factory(int v){  // d
            X r = new X();    
            r.i = v;          
            return r;         
    }                         
}

How can we create an instance of X using this part of codes? I can think of reflection but I think that is too complex. Is there any simpler way to figure out this problem? (Do not add static to factory method and do not delete the private key word of the constructor method).

Upvotes: 0

Views: 83

Answers (1)

Arnaud
Arnaud

Reputation: 17534

You may use a builder inner class like this (main method added for testing purpose, of course you could call X.Builder from outside this class) :

class X {
    private int i;

    private X() {
    }

    public static class Builder {

        public static X factory(final int v) { // d
            X r = new X();
            r.i = v;
            return r;
        }
    }

    public static void main(String[] args) {


        X myX = X.Builder.factory(42);
    }
}

Upvotes: 4

Related Questions