237

通常,我见过人们像这样使用类文字:

Class<Foo> cls = Foo.class;

但是如果类型是泛型的,例如 List 怎么办?这工作正常,但有一个警告,因为 List 应该被参数化:

Class<List> cls = List.class

那么为什么不加一个<?>呢?好吧,这会导致类型不匹配错误:

Class<List<?>> cls = List.class

我认为这样的事情会起作用,但这只是一个普通的语法错误:

Class<List<Foo>> cls = List<Foo>.class

我怎样才能得到一个Class<List<Foo>>静态的,例如使用类文字?

可以用来@SuppressWarnings("unchecked")摆脱第一个示例中由于 List 的非参数化使用而引起的警告Class<List> cls = List.class,但我宁愿不这样做。

有什么建议么?

4

8 回答 8

181

你不能由于类型擦除

Java 泛型只不过是对象转换的语法糖。展示:

List<Integer> list1 = new ArrayList<Integer>();
List<String> list2 = (List<String>)list1;
list2.add("foo"); // perfectly legal

在运行时保留泛型类型信息的唯一实例是Field.getGenericType()通过反射询问类的成员。

这就是为什么Object.getClass()有这个签名:

public final native Class<?> getClass();

重要的部分是Class<?>

换句话说,来自Java Generics FAQ

为什么没有具体参数化类型的类文字?

因为参数化类型没有精确的运行时类型表示。

类文字表示Class 表示给定类型的对象。例如,类字面 量String.class表示Class 表示类型的对象, String并且与在 对象上调用 Class方法时返回的对象相同。类文字可用于运行时类型检查和反射。getClassString

参数化类型在编译期间在称为类型擦除的过程中转换为字节码时会丢失其类型参数。作为类型擦除的副作用,泛型类型的所有实例共享相同的运行时表示,即相应原始类型的表示。换句话说,参数化类型没有自己的类型表示。因此,形成诸如List<String>.class, List<Long>.class和之类的类文字是没有意义的List<?>.class ,因为不Class存在这样的对象。只有原始类型List具有Class 表示其运行时类型的对象。它被称为 List.class

于 2010-03-05T23:39:02.767 回答
72

参数化类型没有 Class 字面量,但是有正确定义这些类型的 Type 对象。

请参阅 java.lang.reflect.ParameterizedType - http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/ParameterizedType.html

Google 的 Gson 库定义了一个 TypeToken 类,该类允许简单地生成参数化类型,并使用它以通用友好的方式指定具有复杂参数化类型的 json 对象。在您的示例中,您将使用:

Type typeOfListOfFoo = new TypeToken<List<Foo>>(){}.getType()

我打算发布 TypeToken 和 Gson 类 javadoc 的链接,但由于我是新用户,Stack Overflow 不允许我发布多个链接,您可以使用 Google 搜索轻松找到它们

于 2010-03-08T04:34:44.410 回答
70

您可以使用双重转换来管理它:

@SuppressWarnings("unchecked") Class<List<Foo>> cls = (Class<List<Foo>>)(Object)List.class

于 2015-06-10T11:29:49.603 回答
9

为了阐述 cletus 的答案,在运行时所有泛型类型的记录都被删除。泛型仅在编译器中处理,用于提供额外的类型安全。它们实际上只是简写,允许编译器在适当的位置插入类型转换。例如,以前您必须执行以下操作:

List x = new ArrayList();
x.add(new SomeClass());
Iterator i = x.iterator();
SomeClass z = (SomeClass) i.next();

变成

List<SomeClass> x = new ArrayList<SomeClass>();
x.add(new SomeClass());
Iterator<SomeClass> i = x.iterator();
SomeClass z = i.next();

这允许编译器在编译时检查您的代码,但在运行时它仍然看起来像第一个示例。

于 2010-03-05T23:44:36.680 回答
4

您可以使用辅助方法来摆脱@SuppressWarnings("unchecked")整个类。

@SuppressWarnings("unchecked")
private static <T> Class<T> generify(Class<?> cls) {
    return (Class<T>)cls;
}

然后你可以写

Class<List<Foo>> cls = generify(List.class);

其他使用示例是

  Class<Map<String, Integer>> cls;

  cls = generify(Map.class);

  cls = TheClass.<Map<String, Integer>>generify(Map.class);

  funWithTypeParam(generify(Map.class));

public void funWithTypeParam(Class<Map<String, Integer>> cls) {
}

但是,由于它很少真正有用,并且该方法的使用会破坏编译器的类型检查,因此我不建议在可公开访问的地方实现它。

于 2016-11-09T23:23:49.243 回答
3

Java Generics FAQ以及因此cletus 的回答听起来好像没有意义Class<List<T>>,但真正的问题是这是非常危险的:

@SuppressWarnings("unchecked")
Class<List<String>> stringListClass = (Class<List<String>>) (Class<?>) List.class;

List<Integer> intList = new ArrayList<>();
intList.add(1);
List<String> stringList = stringListClass.cast(intList);
// Surprise!
String firstElement = stringList.get(0);

cast()使它看起来好像是安全的,但实际上它根本不安全。


虽然我没有得到不能有List<?>.class=的地方,Class<List<?>>因为当您有一个基于Class参数的泛型类型确定类型的方法时,这将非常有帮助。

因为getClass()JDK-6184881请求切换到使用通配符,但是看起来不会(很快)执行此更改,因为它与以前的代码不兼容(请参阅此注释)。

于 2019-01-04T00:36:10.487 回答
2

众所周知,它会被删除。但在类层次结构中明确提及类型的某些情况下,可以知道:

import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public abstract class CaptureType<T> {
    /**
     * {@link java.lang.reflect.Type} object of the corresponding generic type. This method is useful to obtain every kind of information (including annotations) of the generic type.
     *
     * @return Type object. null if type could not be obtained (This happens in case of generic type whose information cant be obtained using Reflection). Please refer documentation of {@link com.types.CaptureType}
     */
    public Type getTypeParam() {
        Class<?> bottom = getClass();
        Map<TypeVariable<?>, Type> reifyMap = new LinkedHashMap<>();

        for (; ; ) {
            Type genericSuper = bottom.getGenericSuperclass();
            if (!(genericSuper instanceof Class)) {
                ParameterizedType generic = (ParameterizedType) genericSuper;
                Class<?> actualClaz = (Class<?>) generic.getRawType();
                TypeVariable<? extends Class<?>>[] typeParameters = actualClaz.getTypeParameters();
                Type[] reified = generic.getActualTypeArguments();
                assert (typeParameters.length != 0);
                for (int i = 0; i < typeParameters.length; i++) {
                    reifyMap.put(typeParameters[i], reified[i]);
                }
            }

            if (bottom.getSuperclass().equals(CaptureType.class)) {
                bottom = bottom.getSuperclass();
                break;
            }
            bottom = bottom.getSuperclass();
        }

        TypeVariable<?> var = bottom.getTypeParameters()[0];
        while (true) {
            Type type = reifyMap.get(var);
            if (type instanceof TypeVariable) {
                var = (TypeVariable<?>) type;
            } else {
                return type;
            }
        }
    }

    /**
     * Returns the raw type of the generic type.
     * <p>For example in case of {@code CaptureType<String>}, it would return {@code Class<String>}</p>
     * For more comprehensive examples, go through javadocs of {@link com.types.CaptureType}
     *
     * @return Class object
     * @throws java.lang.RuntimeException If the type information cant be obtained. Refer documentation of {@link com.types.CaptureType}
     * @see com.types.CaptureType
     */
    public Class<T> getRawType() {
        Type typeParam = getTypeParam();
        if (typeParam != null)
            return getClass(typeParam);
        else throw new RuntimeException("Could not obtain type information");
    }


    /**
     * Gets the {@link java.lang.Class} object of the argument type.
     * <p>If the type is an {@link java.lang.reflect.ParameterizedType}, then it returns its {@link java.lang.reflect.ParameterizedType#getRawType()}</p>
     *
     * @param type The type
     * @param <A>  type of class object expected
     * @return The Class<A> object of the type
     * @throws java.lang.RuntimeException If the type is a {@link java.lang.reflect.TypeVariable}. In such cases, it is impossible to obtain the Class object
     */
    public static <A> Class<A> getClass(Type type) {
        if (type instanceof GenericArrayType) {
            Type componentType = ((GenericArrayType) type).getGenericComponentType();
            Class<?> componentClass = getClass(componentType);
            if (componentClass != null) {
                return (Class<A>) Array.newInstance(componentClass, 0).getClass();
            } else throw new UnsupportedOperationException("Unknown class: " + type.getClass());
        } else if (type instanceof Class) {
            Class claz = (Class) type;
            return claz;
        } else if (type instanceof ParameterizedType) {
            return getClass(((ParameterizedType) type).getRawType());
        } else if (type instanceof TypeVariable) {
            throw new RuntimeException("The type signature is erased. The type class cant be known by using reflection");
        } else throw new UnsupportedOperationException("Unknown class: " + type.getClass());
    }

    /**
     * This method is the preferred method of usage in case of complex generic types.
     * <p>It returns {@link com.types.TypeADT} object which contains nested information of the type parameters</p>
     *
     * @return TypeADT object
     * @throws java.lang.RuntimeException If the type information cant be obtained. Refer documentation of {@link com.types.CaptureType}
     */
    public TypeADT getParamADT() {
        return recursiveADT(getTypeParam());
    }

    private TypeADT recursiveADT(Type type) {
        if (type instanceof Class) {
            return new TypeADT((Class<?>) type, null);
        } else if (type instanceof ParameterizedType) {
            ArrayList<TypeADT> generic = new ArrayList<>();
            ParameterizedType type1 = (ParameterizedType) type;
            return new TypeADT((Class<?>) type1.getRawType(),
                    Arrays.stream(type1.getActualTypeArguments()).map(x -> recursiveADT(x)).collect(Collectors.toList()));
        } else throw new UnsupportedOperationException();
    }

}

public class TypeADT {
    private final Class<?> reify;
    private final List<TypeADT> parametrized;

    TypeADT(Class<?> reify, List<TypeADT> parametrized) {
        this.reify = reify;
        this.parametrized = parametrized;
    }

    public Class<?> getRawType() {
        return reify;
    }

    public List<TypeADT> getParameters() {
        return parametrized;
    }
}

现在您可以执行以下操作:

static void test1() {
        CaptureType<String> t1 = new CaptureType<String>() {
        };
        equals(t1.getRawType(), String.class);
    }

    static void test2() {
        CaptureType<List<String>> t1 = new CaptureType<List<String>>() {
        };
        equals(t1.getRawType(), List.class);
        equals(t1.getParamADT().getParameters().get(0).getRawType(), String.class);
    }


    private static void test3() {
            CaptureType<List<List<String>>> t1 = new CaptureType<List<List<String>>>() {
            };
            equals(t1.getParamADT().getRawType(), List.class);
        equals(t1.getParamADT().getParameters().get(0).getRawType(), List.class);
    }

    static class Test4 extends CaptureType<List<String>> {
    }

    static void test4() {
        Test4 test4 = new Test4();
        equals(test4.getParamADT().getRawType(), List.class);
    }

    static class PreTest5<S> extends CaptureType<Integer> {
    }

    static class Test5 extends PreTest5<Integer> {
    }

    static void test5() {
        Test5 test5 = new Test5();
        equals(test5.getTypeParam(), Integer.class);
    }

    static class PreTest6<S> extends CaptureType<S> {
    }

    static class Test6 extends PreTest6<Integer> {
    }

    static void test6() {
        Test6 test6 = new Test6();
        equals(test6.getTypeParam(), Integer.class);
    }



    class X<T> extends CaptureType<T> {
    }

    class Y<A, B> extends X<B> {
    }

    class Z<Q> extends Y<Q, Map<Integer, List<List<List<Integer>>>>> {
    }

    void test7(){
        Z<String> z = new Z<>();
        TypeADT param = z.getParamADT();
        equals(param.getRawType(), Map.class);
        List<TypeADT> parameters = param.getParameters();
        equals(parameters.get(0).getRawType(), Integer.class);
        equals(parameters.get(1).getRawType(), List.class);
        equals(parameters.get(1).getParameters().get(0).getRawType(), List.class);
        equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getRawType(), List.class);
        equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getParameters().get(0).getRawType(), Integer.class);
    }




    static void test8() throws IllegalAccessException, InstantiationException {
        CaptureType<int[]> type = new CaptureType<int[]>() {
        };
        equals(type.getRawType(), int[].class);
    }

    static void test9(){
        CaptureType<String[]> type = new CaptureType<String[]>() {
        };
        equals(type.getRawType(), String[].class);
    }

    static class SomeClass<T> extends CaptureType<T>{}
    static void test10(){
        SomeClass<String> claz = new SomeClass<>();
        try{
            claz.getRawType();
            throw new RuntimeException("Shouldnt come here");
        }catch (RuntimeException ex){

        }
    }

    static void equals(Object a, Object b) {
        if (!a.equals(b)) {
            throw new RuntimeException("Test failed. " + a + " != " + b);
        }
    }

更多信息在这里。但同样,几乎不可能检索到:

class SomeClass<T> extends CaptureType<T>{}
SomeClass<String> claz = new SomeClass<>();

它被抹去的地方。

于 2015-04-27T10:00:59.553 回答
1

由于 Class literals 没有泛型类型信息这一事实,我认为您应该假设不可能摆脱所有警告。在某种程度上,使用Class<Something>与使用集合而不指定泛型类型相同。我能得出的最好的结果是:

private <C extends A<C>> List<C> getList(Class<C> cls) {
    List<C> res = new ArrayList<C>();
    // "snip"... some stuff happening in here, using cls
    return res;
}

public <C extends A<C>> List<A<C>> getList() {
    return getList(A.class);
}
于 2010-03-08T14:34:39.330 回答