CKTIS / Java
Refleksja generycznej nadklasy i interfejsów w Javie
Odczytaj zadeklarowane typy bezpośredniej nadklasy i interfejsów. Dowiedz się, dlaczego z klasy zwykłej instancji `ArrayList<String>` nie odzyskasz argumentu `String`.
Wersja: Java SE 21
Składnia
public java.lang.reflect.Type getGenericSuperclass()
public java.lang.reflect.Type[] getGenericInterfaces()Class.getGenericSuperclass() zwraca bezpośrednią nadklasę jako java.lang.reflect.Type. Dla Object, interfejsu, typu prymitywnego i void zwraca null, a dla typu tablicowego — Object.class.
Class.getGenericInterfaces() zwraca Type[] z interfejsami bezpośrednio implementowanymi przez klasę lub rozszerzanymi przez interfejs, w kolejności z deklaracji. Nie przeszukuje hierarchii. Gdy takich interfejsów nie ma, również dla typów prymitywnych i void, zwraca pustą tablicę. Dla typu tablicowego zwraca kolejno Cloneable i java.io.Serializable.
W przeciwieństwie do getSuperclass() i getInterfaces(), które zwracają obiekty Class bez argumentów typów, warianty generyczne mogą zwrócić ParameterizedType. Zanim wywołasz getActualTypeArguments(), sprawdź wynik za pomocą instanceof ParameterizedType. Argumenty mają typ Type: mogą reprezentować konkretną klasę, zagnieżdżony typ parametryzowany lub zmienną typu, a sam typ surowy, np. List bez argumentów, jest reprezentowany przez Class.
Te metody odczytują sygnaturę deklaracji, a nie argument typu przypisany konkretnej instancji. Wskutek wymazywania typów new ArrayList<String>().getClass() daje tę samą klasę co ArrayList.class: jej nadklasą jest AbstractList<E>, gdzie E to TypeVariable, a nie String. Natomiast deklaracja extends ArrayList<String> w podklasie zapisuje String w jej sygnaturze.
Obie metody mogą zgłosić GenericSignatureFormatError, gdy format sygnatury jest niepoprawny, TypeNotPresentException, gdy brakuje wskazanego typu, lub MalformedParameterizedTypeException, gdy nie można utworzyć reprezentacji typu parametryzowanego.
Przykłady
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<?>));
}
}Wynik
Names superclass argument is String: true Names interface argument is Integer: true ArrayList superclass argument is a type variable: true
`Names` deklaruje dokładnie jeden bezpośredni interfejs, więc przykład używa indeksu `0`. Pierwsze dwa testy odczytują `String` i `Integer` z deklaracji `Names`, a trzeci potwierdza, że argumentem nadklasy zwykłej `ArrayList` jest zmienna typu `E`.
Powiązane lekcje
- Java · Lekcja 36 · Średniozaawansowany · Wersja: 2