Generics


stáhnout snippet
zobrazení: SyntaxHighlighter | GeSHi | Holý text
package cz.instance.liferay.gtt;

import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class GenericType<T> {

	private final Type type;
	private volatile Constructor<T> constructor;

	protected GenericType() {
		Type superClass = getClass().getGenericSuperclass();
		if (superClass instanceof Class<?>) {
			throw new IllegalArgumentException("GenericType constructed without generic type parameter");
		}
		type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
	}

	public Type getType() {
		return type;
	}

	public T newInstance() throws Exception {
		return getConstructor().newInstance();
	}

	public Constructor<T> getConstructor() throws Exception {
		constructor = constructor != null ? constructor : getClazz().getConstructor();
		return constructor;
	}

	@SuppressWarnings("unchecked")
	public Class<T> getClazz() {
		Class<?> clazz = type instanceof Class<?> ? (Class<?>) type : (Class<?>) ((ParameterizedType) type).getRawType();
		return (Class<T>) clazz;
	}
}


java 39 řádků | 2011-10-11 22:12:22