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>>クラスリテラルなどを使用して静的に取得するにはどうすればよいですか?

最初の例でパラメータ化されていない List を使用したために発生した警告を取り除くために を使用することもできますが、私はそうはしません。@SuppressWarnings("unchecked")Class<List> cls = List.class

助言がありますか?

4

8 に答える 8

181

タイプ eraserのため、できません。

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.classClass 、型を表すオブジェクトを 示し、オブジェクトでメソッドが呼び出された ときに返されるオブジェクトStringと同じです 。クラス リテラルは、実行時の型チェックとリフレクションに使用できます。ClassgetClassString

パラメーター化された型は、型消去と呼ばれるプロセスでコンパイル中にバイト コードに変換されると、型引数を失います。型消去の副作用として、ジェネリック型のすべてのインスタンス化は、同じ実行時表現、つまり対応する生の型の表現を共有します。つまり、パラメータ化された型には、独自の型表現がありません。したがって、 、 、 などのクラス リテラルを作成しても意味がありません。List<String>.classその ようなオブジェクトは存在しないからです。生の型だけが、 その実行時の型を表すオブジェクトを持ちます。と呼ばれ ます。List<Long>.classList<?>.classClassListClassList.class

于 2010-03-05T23:39:02.767 に答える
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 に答える
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<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 に答える