Java是否允许我将此对象分配给此通用字段?

时间:2018-08-25 17:38:41

标签: java generics reflection guava

在我的POJO编辑器中,我需要检查是否可以实例化用户提供的类名并将其分配给泛型属性。番石榴反射几乎提供了我需要的所有内容:我解析了类型,然后调用proptype.isSupertypeOf(implClazz),但这无法正常工作。

例如,我有类型标记:java.util.Collection<java.sql.Timestamp>,并且我希望我的支票接受ArrayList,并且扩展了原始ArrayListArrayList<Timestamp>或本身扩展的类,但不接受扩展ArrayList<Integer>的类。

但是,isSupertypeOf()仅适用于完全解析的类型,而不完整和原始类则不被视为子类型。

    package com.common.jsp.beans;

    import java.lang.reflect.Field;
    import java.lang.reflect.Type;
    import java.sql.Timestamp;
    import java.util.ArrayList;
    import java.util.Collection;

    import com.google.common.reflect.TypeToken;

    public class TestTypeInf
    {
        public static class MyCollection1 extends ArrayList<Integer> {
        }
        public static class MyCollection2 extends ArrayList<Timestamp> {
        }
        public static class MyCollection3<T> extends ArrayList<T> {
        }
        public static class MyCollection4 extends ArrayList {
        }

        public static Collection<Timestamp> fld;

        public static void main( String[] args )
                        throws Exception
        {
            // bad: fld = new MyCollection1();
            fld = new MyCollection2();
            fld = new MyCollection3(); // just a warning
            fld = new MyCollection4(); // just a warning

            Field getter = TestTypeInf.class.getField( "fld" );
            Type memberType = getter.getGenericType();

            TypeToken<?> resolved = TypeToken.of( TestTypeInf.class ).resolveType( memberType );
            System.out.println( "type of fld: " + resolved );

            checkAssignable(resolved, MyCollection1.class);
            checkAssignable(resolved, MyCollection2.class);
            checkAssignable(resolved, MyCollection3.class); // This should be totally valid
            checkAssignable(resolved, MyCollection4.class); // why no?
        }

        private static void checkAssignable(TypeToken<?> resolved, Class<?> implClass) {
            System.out.println( "fld = new " + implClass.getSimpleName() + "()" );
            System.out.println( resolved.isSupertypeOf( implClass ) ? "yes" : "no" );
        }
    }

_

type of fld: java.util.Collection<java.sql.Timestamp>
fld = new MyCollection1()
no
fld = new MyCollection2()
yes
fld = new MyCollection3()
no
fld = new MyCollection4()
no
fld = new ArrayList()
no

1 个答案:

答案 0 :(得分:1)

这确实很hacky,但是由于您尝试做的也很hacky(即尝试以反射方式确定在编译器中引发未经检查的警告的分配),我认为这是合理的:

private static boolean isAssignable(TypeToken<?> resolved, Class<?> implClass) {
    return resolved.isSupertypeOf(implClass) || isAnySupertypeAssignable(resolved, implClass);
}

private static boolean isAnySupertypeAssignable(TypeToken<?> resolved, Class<?> implClass) {
    return TypeToken.of(implClass).getTypes().stream()
            .anyMatch(supertype -> isUncheckedSupertype(resolved, supertype));
}

private static boolean isUncheckedSupertype(TypeToken<?> resolved, TypeToken<?> implTypeToken) {
    if (implTypeToken.getType() instanceof ParameterizedType) {
        return false; // this prevents assignments of Collection<Integer> to Collection<Timestamp>
    }
    try {
        resolved.getSubtype(implTypeToken.getRawType());
        return true;
    } catch (IllegalArgumentException ex) {
        return false;
    }
}

我在您的示例中对其进行了检查,并返回:

fld = new MyCollection1() -> no
fld = new MyCollection2() -> yes
fld = new MyCollection3() -> yes
fld = new MyCollection4() -> yes
fld = new ArrayList() -> yes