简体   繁体   English

矛盾地转换番石榴谓词

[英]Contravariantly converting Guava Predicates

I have a Predicate<Object> and need an equivalent Predicate<Animal> . 我有一个Predicate<Object> ,需要一个等效的Predicate<Animal>

Predicate<Animal> provideIsSentientPredicate() {
    // Won't compile -- cannot convert from Predicate<Object> to Predicate<Animal>
    return Predicates.instanceOf(Human.class);
}

Predicates are contravariant, so converting a Predicate<Object> to a Predicate<Animal> is safe. 谓词是逆变的,因此将Predicate<Object>转换为Predicate<Animal>是安全的。 Is there clean and readable way to convert from a Predicate<Object> to a Predicate<Animal> (eg without suppressing warnings)? 是否有清晰易读的方式从Predicate<Object>转换为Predicate<Animal> (例如,不抑制警告)?

I'd prefer not to change my method's type signature to return a Predicate<? super Animal> 我宁愿不改变我的方法的类型签名来返回Predicate<? super Animal> Predicate<? super Animal> or Predicate<Object> unless someone convinces me that is the correct thing to do. Predicate<? super Animal>Predicate<Object>除非有人说服我这是正确的事情。

Predicate<Animal> provideIsSentientPredicate() 
{
    return cast( Predicates.instanceOf(Human.class) );
}

static <A, B extends A> Predicate<B> cast(Predicate<A> pa)
{
    @SuppressWarnings("unchecked")
    Predicate<B> pb = (Predicate)(pa);
    return pb;

    // we know it works correctly in practice.
    // or if you are a theorist, create a wrapper predicate
    //
    //     Predicate<B>
    //         boolean apply(B b)
    //             return pa.apply(b);
}

BTW, there's no reason why Guava shouldn't declare the method as 顺便说一下,没有理由为什么Guava不应该声明这个方法

static <T> Predicate<T> instanceOf(Class<?> clazz)

consistent with other sibling methods. 与其他兄弟方法一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM