确保通用lambda表达式的类型安全性

时间:2017-05-15 17:37:53

标签: java generics reflection lambda java-8

这是对Java8 retrieving lambda setter from class的一些跟进。

我试图获得给定字段的getter方法

public <T, R> IGetter<T, R> getGetter(Class<T> clazz, Field field) {

    Class<R> fieldType = null;
    try {
        fieldType = (Class<R>) field.getType();
    } catch(ClassCastException e) {
        error("Attempted to create a mistyped getter for the field " + field + "!");
    }

    return getGetter(clazz, field.getName(), fieldType);
}

这是基本方法:

public <T, R> IGetter<T, R> getGetter(Class<T> clazz, String fieldName, Class<R> fieldType) {

    MethodHandles.Lookup caller = null;
    MethodHandle target = null;
    MethodType func = null;

    try {
        caller = MethodHandles.lookup();
        MethodType getter = MethodType.methodType(fieldType);
        target = caller.findVirtual(clazz, computeGetterName(fieldName), getter);
        func = target.type();
    } catch (NoSuchMethodException e) {
        error("Could not locate a properly named getter \"" + computeGetterName(fieldName) + "\"!");
    } catch (IllegalAccessException e) {
        error("Could not access \"" + computeGetterName(fieldName) + "\"!");
    }

    CallSite site = null;
    try {
        site = LambdaMetafactory.metafactory(
                caller,
                "get",
                MethodType.methodType(IGetter.class),
                func.generic(),
                target,
                func
        );
    } catch (LambdaConversionException e) {
        error("Could not convert the getter \"" + computeGetterName(fieldName) + "\" into a lambda expression!");
    }

    MethodHandle factory = site.getTarget();

    IGetter<T, R> r = null;
    try {
        r = (IGetter<T, R>) factory.invoke();
    } catch (Throwable throwable) {
        error("Casting the factory of \"" + computeGetterName(fieldName) + "\" failed!");
    }

    return r;
}

由于类型不匹配,这不能编译:

IGetter<TestEntity, Long> getter = accessorFactory.getGetter(TestEntity.class, "name", String.class);

但是这会编译:

Field field = TestEntity.class.getDeclaredField("name");
IGetter<TestEntity, Long> getter = accessorFactory.getGetter(TestEntity.class, field);

令我惊讶的是,这确实可以使用上面检索到的getter:

TestEntity testEntity = new TestEntity(1L, "Test");
System.out.println(getter.get(testEntity));

然而,一旦我这样做了:

Long value = getter.get(testEntity);

我得到以下异常:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
    at de.cyclonit.exercise.Main.main(Main.java:26)

有没有办法早点抓住这个?

TestEntity类:

public class TestEntity {

    private Long id;

    private String name;


    public TestEntity(Long id, String name) {
    this.id = id;
        this.name = name;
    }


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
}

1 个答案:

答案 0 :(得分:7)

问题是你的方法

public <T, R> IGetter<T, R> getGetter(Class<T> clazz, Field field) {
    Class<R> fieldType = null;
    try {
        fieldType = (Class<R>) field.getType();
    } catch(ClassCastException e) {
        error("Attempted to create a mistyped getter for the field " + field + "!");
    }
    return getGetter(clazz, field.getName(), fieldType);
}

实际上并没有执行检查。您基本上是将Class实例强制转换为Class,但这种情况无效。将泛型类型Class<?>更改为Class<R>是纯编译时的事情,这就是为什么此时应该获得“未经检查”的警告,至少在所有警告都已启用的情况下。 / p>

在运行时进行实际检查的唯一方法是从调用者那里获得预期的类型:

public <T, R> IGetter<T, R> getGetter(Class<T> clazz, Class<R> fieldType, Field field) {
    if(fieldType != field.getType()) {
        error("Attempted to create a mistyped getter for the field " + field + "!");
    }
    return getGetter(clazz, field.getName(), fieldType);
}

当然,这使得接受Field的方法有点无意义。实际的getGetter已经执行了一次查找,需要与getter的返回类型完全匹配,并且你不需要获得字段的类型和getter的返回类型必须匹配。实际上,它会对内部细节产生不必要的依赖。

为什么不简单地注释getter而不是字段......