Java – a generic Java class instantiation example

public class CommandFactory {
    public static <T extends Command<R>, R extends CommandResult> T createCommand(Class<T> classObject, Object... params) {
        try {
            T newInstance = classObject.newInstance();
            if (newInstance.initialize(params)) {
                return newInstance;
            }
        } catch (Exception e) {

        }
        assert false;
        return null;
    }
}

public class TestCommandResult extends CommandResult {
}

public class TestCommand extends Command<TestCommandResult> {
    private int index;
    public TestCommand() {
    }

    public bool initialize(int idx) {
        this.index = idx;
    }
}

TestCommand testCmd = CommandFactory.<TestCommand, TestCommandResult>createCommand(TestCommand.class, 1);

Advertisements
This entry was posted in Java, Programming and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s