Class von “Type Parameter” – Java Generics (gepimpt)

Meine Lösung von gestern funktioniert nicht, wenn die Klassenhierarchy tiefer als Eins ist. Die Methode getGenericSuperclass() liefert eben nur die Superklasse der aktuellen Klasse. Es ist also noch notwendig die Hierarchie nach Dada zu suchen um die Typinformation zu bekommen:

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

public class Parameterized {
    public static void main(String[] args) {
        new SubDada();
        new SubSubDada();
    }
}

abstract class Dada {
    private Class typeOfT;
    public Dada() {
        this.typeOfT = getTypeOfT();
        System.out.println("typeOfT: " + this.typeOfT);
    }
    @SuppressWarnings("unchecked")
    private Class getTypeOfT() {
        ParameterizedType pType = getDadaAsParameterizedType(getClass());
        return (Class) pType.getActualTypeArguments()[0];
    }
    private ParameterizedType getDadaAsParameterizedType(Class clazz) {
        Object gstype = clazz.getGenericSuperclass();
        if (gstype instanceof ParameterizedType) {
            ParameterizedType ptype = (ParameterizedType) gstype;
            Type rawtype = ptype.getRawType();
            if (Dada.class.equals(rawtype)) {
                return ptype;
            }
        }
        return getDadaAsParameterizedType(clazz.getSuperclass());
    }
}

class SubDada extends Dada {
    public SubDada() {
    }
}

class SubSubDada extends SubDada {
    public SubSubDada() {
    }
}

Leave a Reply

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

WordPress.com Logo

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s