Showing posts with label Generic. Show all posts
Showing posts with label Generic. Show all posts

Tuesday, November 8, 2011

Creating an Array from a Generic class type

Well, I didn't figure this out quick enough but it is as simple as:


@SuppressWarnings("unchecked")
protected final <ArrayType> ArrayType[] getArray(Class<ArrayType> arrayType, int size) {
return (ArrayType[]) Array.newInstance(arrayType, size);
}

Ridicules isn't it...? 
My architecture for a long time was lacking because I was missing this info, and in combination with this post, it makes Generics the most useful feature while designing an application architecture.

Monday, November 7, 2011

Getting Java generic parameter types in runtime

For the long while I was using Java Generic types, in Methods, Fields and Classes, and I used to transfer the Class type instance as a parameter to the constructor or method respectively. Lately I've learned how Java's Generic types, can be determine in runtime.

To get the generic types of a Class:

abstract class ClassWithGenericParameterType<ItemType>  {
private Class<ItemType> itemType;
ClassWithGenericParameterType() {
ParameterizedType classType = (ParameterizedType) getClass().getGenericSuperclass();
Type[] types = classType.getActualTypeArguments();
itemType= (Class<ItemType>) types[0];
}
}

To make this work:

class ExtendingParameterizedGenericClass extends ClassWithGenericParameterType<String> {...}
Thing is about this trick, is that the class you are analyzing must be abstract, and that a new Class would extend that abstract class specifying a valid Class as the Generic argument and not something like <ItemType2 extends Number>, this would result in getting Number.class!