Check Generic type

Using JMS which is not implemented with Generics, I decided to add some “genericity”.
The problem is that, because of type erasure, I can’t use the simple instanceof operator, the solution I used is to pass the class of the Generic when I use it:


public class Handler {

    public Handler() {
    private Class clazz;

    public Handler(Class clazz) {
        this.clazz = clazz;

    public T extract(Object o) {
        if (!(o.getClass().isAssignableFrom(clazz)))
            throw new RuntimeException("explicite message");
        return (T) o;
    public static void main(String[] args) {
        Handler handler = new Handler(String.class);
        System.out.println(handler.extract(new Integer("11")));//This throw an Exception
        System.out.println(handler.extract(new Integer("11")));//This is ok

Now it works, but I will try to find a more elegant solution to avoid the clazz parameter.

Leave a comment