Znalostní bázeCentrum zkoušek
CSČeština
Vybrat jazyk13

CKTIS / Java

Zkoumání generických nadtříd a rozhraní v Javě

Přečti deklarované typy přímé nadtřídy a přímých rozhraní a zjisti, proč z běhové třídy běžné instance `ArrayList<String>` nelze získat argument `String`.

Verze: Java SE 21

Syntaxe

public java.lang.reflect.Type getGenericSuperclass()
public java.lang.reflect.Type[] getGenericInterfaces()

Class.getGenericSuperclass() vrací přímou nadtřídu jako java.lang.reflect.Type. Pro Object, rozhraní, primitivní typy a void vrací null, pro typy polí vrací Object.class.

Class.getGenericInterfaces() vrací Type[] s rozhraními, která třída přímo implementuje nebo která rozhraní přímo rozšiřuje, v pořadí deklarace. Neprochází hierarchii. Pokud taková rozhraní nejsou, například u primitivních typů a void, je pole prázdné. Pro typy polí výsledek obsahuje nejprve Cloneable a poté java.io.Serializable.

Na rozdíl od getSuperclass() a getInterfaces(), které vracejí objekty Class bez typových argumentů, mohou generické metody poskytnout ParameterizedType, u rozhraní jako prvek pole. Před voláním getActualTypeArguments() ověř typ pomocí instanceof ParameterizedType. Argumenty jsou hodnoty Type: mohou představovat konkrétní třídy, vnořené parametrizované typy nebo typové proměnné. Surový nadtyp, například List bez argumentů, představuje Class.

Tyto metody čtou signatury deklarací, nikoli typové argumenty jednotlivých instancí. Kvůli mazání typů dává new ArrayList<String>().getClass() stejnou třídu jako ArrayList.class: její nadtřída je AbstractList<E>, kde E je TypeVariable, nikoli String. Podtřída deklarovaná s extends ArrayList<String> naopak zaznamenává String ve vlastní signatuře.

Obě metody mohou vyvolat GenericSignatureFormatError při neplatném formátu signatury, TypeNotPresentException, pokud odkazovaný typ chybí, nebo MalformedParameterizedTypeException, pokud parametrizovaný typ nelze vytvořit.

Příklady

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;

public class GenericSupertypesDemo {
    interface Tagged<T> {}

    static final class Names extends ArrayList<String> implements Tagged<Integer> {}

    private static Type singleArgument(Type type) {
        if (type instanceof ParameterizedType parameterized) {
            Type[] arguments = parameterized.getActualTypeArguments();
            if (arguments.length == 1) {
                return arguments[0];
            }
        }
        throw new IllegalArgumentException("Expected a type with one type argument");
    }

    public static void main(String[] args) {
        Type parent = Names.class.getGenericSuperclass();
        Type tagged = Names.class.getGenericInterfaces()[0];
        Type plainParent = new ArrayList<String>().getClass().getGenericSuperclass();

        System.out.println("Names superclass argument is String: "
                + String.class.equals(singleArgument(parent)));
        System.out.println("Names interface argument is Integer: "
                + Integer.class.equals(singleArgument(tagged)));
        System.out.println("ArrayList superclass argument is a type variable: "
                + (singleArgument(plainParent) instanceof TypeVariable<?>));
    }
}

Výsledek

Names superclass argument is String: true
Names interface argument is Integer: true
ArrayList superclass argument is a type variable: true

`Names` deklaruje právě jedno přímé rozhraní, proto příklad používá index `0`. První dvě kontroly načtou `String` a `Integer` z deklarace `Names`; třetí potvrzuje, že argumentem nadtřídy běžné `ArrayList` je typová proměnná `E`.

Související lekce

  • Java · Lekce 36 · Středně pokročilá · Verze: 2

Zdroje