views:

64

answers:

2

I have a class say 'A', an object 'a' of which creates an object 'b' of class'B'. Now 'b' runs a method which wants to create a new instance of b's parent(please dont confuse it with inheritance) - the class which created 'b', which is 'A' as in here.

Is this anyhow possible in Java ? Or maybe some design suggestion may work.

Thanks !

Edit : As per suggestions, I am adding my design requirement too. I have an "ExitController" class, which works differently as per the caller function - like if it is invoked by a UserX, it terminates program, if it is invoked by a UserY it logs him off, etc. Typically I should be placing an ExitController method in my User interface, but there are some constraints due to which I cant. Also, passing the parent object/classname is seeming very expensive compared to the use it offers.

+5  A: 

Basically, you've to pass the parent itself or the parent type into B's constructor. The below example illustrates the last case.

class A {
    B b;

    A() { 
        b = new B(getClass());
    }
}

class B {
    Class<?> parentClass;

    B(Class<?> parentClass) {
        this.parentClass = parentClass;
    }

    void createParent() throws Exception {
        Object o = parentClass.newInstance();
    }
}

With generics you could make it more type safe. But since the functional requirement is not entirely clear, I've left that away.


Update as per your update, creating instances is pointless. You could just check the class type and handle accordingly. Instead of createParent() in above example, do:

void exit() {
    if (parentClass == UserX.class) {
        // Terminate program.
    } else if (parentClass == UserY.class) {
        // Logoff user.
    }
}

This is however plain ugly. Are you really not allowed to add another method to the User interface? Otherwise the following would be a better design (called the Strategy pattern):

interface User {
    void exit();
}

class ExitController {
    void exit(User user) {
        user.exit();
    }
}

class UserX implements User {
    public void exit() {
        // Terminate program.
    }
}

class UserY implements User {
    public void exit() {
        // Logoff user.
    }
}

As per your last statement:

Also, passing the parent object/classname is seeming very expensive compared to the use it offers

This makes no sense. Have you measured it? Show us the results.

BalusC
Couldn't have done it better myself....
The Elite Gentleman
A: 

If I understand your question correctly, I think that class B would have to store a reference to either object a or A.class. That would allow b to construct a new instance of A. The simplest way to to do this would be for B's constructor to take a class argument.

Steve Emmerson