geeky · java

Java Generics – conditionally instantiate a class

From Class to list of Enums

public static <T extends Enum> List<T> getList(Class<T> clazz) {
    return Arrays.asList(clazz.getEnumConstants());

So if I want to instantiate a class via some condition, I can do the following but still how do I know what type to use?

public class Foo {
	public String getName() {
		return "hi";
public class Foo2013 extends Foo {
	public String getAge() {
		return "age";
public class FooFactory {
	@SuppressWarnings("unchecked") // what do I need to do to not having to use this??
	public static <F extends Foo> F getFoo(int year) {
		try {
			if (year >= 2013) {
				return (F) Foo2013.class.newInstance();
			} else {
				return (F) Foo.class.newInstance();
		} catch (InstantiationException e) {
			// TODO
		} catch (IllegalAccessException e) {
			// TODO
		return null;
public class FooFactoryTest {
	public void testFooFactory() {
		Foo foo = FooFactory.getFoo(2011);
		Assert.assertEquals(Foo.class, foo.getClass());

		Foo foo2013 = FooFactory.getFoo(2013);  // <-- how can I do Foo2013 foo2013 without repeating the logic?
//		foo2013.getAge();
		Assert.assertEquals(Foo2013.class, foo2013.getClass());

Leave a Reply

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

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

Facebook photo

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

Connecting to %s