Quantcast
Channel: Pure-Essence.Net » java
Viewing all articles
Browse latest Browse all 10

Java Generics – conditionally instantiate a class

$
0
0

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 {
	@Test
	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());
	}
}

https://github.com/dodozhang21/JavaGenerics



Viewing all articles
Browse latest Browse all 10

Trending Articles