0

I have some classes that I want to initialize only if the passed parameter is true. It turns out that every implementaion of this method is the same, but is just used for a different class.

public static NamedScene getScene(boolean init) {
    if (mainMenu == null) {
        mainMenu = new MainMenu();
    }
    if (init) mainMenu.init();
    return mainMenu;
}

I would like to abstract this method, so I won't have to access it manually via calling MainMenu.init(true); but with scene.init(true); where scene extends the abstract class.

There are some default properties for every class, like name that is acessed via the abstract method getName(). I expect the method to sometimes return the class instance without init(), and sometimes with init().

NightRa
  • 10,701
  • 3
  • 16
  • 22

1 Answers1

0

Consider using a generic method for this.
It's not the exact code you wanted, but you will understand from it:

  public static <T> T conditionalInit(Class<T> clazz, boolean okToInit) {
    try {
      return okToInit?clazz.newInstance() : null;
    } catch (Exception e) {
      return null;
    }
 }

Usage:

Person p = conditionalInit(Person.class, true); //not null
Person p2 = conditionalInit(Person.class, false); //null

Comments:
1. If you must execute an "init" method, I suggest all your classes implement an Initializable interface which will contain an "init" method.
And then the signature of the method will be:
public static T conditionalInit(Class clazz, boolean okToInit)


2. I remind you that a static generic method can exist in a non generic class.

Yair Zaslavsky
  • 4,091
  • 4
  • 20
  • 27
  • The point is, I don't want to return null. There are some default properties for every class, like name that is acessed via the abstract method getName(). I expect the method to sometimes return the class instance without init(), and sometimes with init(). – NightRa Nov 08 '12 at 20:31
  • @NightRa: i think a more detailed example of what you're trying to achieve would be helpful – Andrey Nov 08 '12 at 21:35