gpt4 book ai didi

java - 在三元中使用无界泛化静态函数时如何避免未经检查的强制转换?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:47:12 25 4
gpt4 key购买 nike

我想弄清楚是否有办法避免在此函数中进行未经检查的强制转换(使用 Java 7):

private static <O> ValueValidator<O> newForAlways(Always valid_orInvalid)  {
@SuppressWarnings("unchecked")
ValueValidator<O> vldtr = (ValueValidator<O>)(valid_orInvalid == Always.VALID
? newForAlwaysValid()
: newForAlwaysInvalid());
return vldtr;
}

这是返回的两个函数的签名:

private static <O> ValueValidator<O> newForAlwaysValid()  {
private static <O> ValueValidator<O> newForAlwaysInvalid() {

(这里是 Always 枚举,它只是一个 boolean 值替代:

enum Always {VALID, INVALID;};

)

所有三个函数都具有相同的返回类型并包含无界泛型。这两个问题解释了为什么会发生,尽管它们都是关于有界泛型的:

所以即使这有效

ValueValidator<Integer> intVldtr = Test.<Integer>newForAlwaysValid();

这不是:

private static <O> ValueValidator<O> newForAlways(Always valid_orInvalid)  {
return (valid_orInvalid == Always.VALID
? <O>newForAlwaysValid()
: <O>newForAlwaysInvalid());
}

C:\java_code\Test.java:15: error: illegal start of expression
? <O>newForAlwaysValid()

...and 8 more similar errors...

这也不是:

private static <O> ValueValidator<O> newForAlways2(Always valid_orInvalid)  {
return (valid_orInvalid == Always.VALID
? newForAlwaysValid()
: newForAlwaysInvalid());
}

C:\java_code\Test.java:15: error: incompatible types
? newForAlwaysValid()
^
required: ValueValidator<O>
found: ValueValidator<Object>
where O is a type-variable:
O extends Object declared in method <O>newForAlways2(Always)

那么,再重复一遍这个问题:除了 unchecked cast 之外,还有其他选择吗? (我使用的是 Java 7。)

SSCCE :

public class Test  {
public static void main(String[] ignored) {
ValueValidator<Integer> intVldtr = Test.<Integer>newForAlwaysValid();
intVldtr = Test.<Integer>newForAlways(Always.VALID);
}
private static <O> ValueValidator<O> newForAlways(Always valid_orInvalid) {
@SuppressWarnings("unchecked")
ValueValidator<O> vldtr = (ValueValidator<O>)(valid_orInvalid == Always.VALID
? newForAlwaysValid()
: newForAlwaysInvalid());
return vldtr;
}
private static <O> ValueValidator<O> newForAlwaysValid() {
return (new AlwaysValid<O>());
}
private static <O> ValueValidator<O> newForAlwaysInvalid() {
return (new AlwaysInvalid<O>());
}
}
enum Always {VALID, INVALID;};
abstract class ValueValidator<O> {
public abstract boolean isValid(O to_validate);
}
class AlwaysValid<O> extends ValueValidator<O> {
public boolean isValid(O to_validate) {
return true;
}
}
class AlwaysInvalid<O> extends ValueValidator<O> {
public boolean isValid(O to_validate) {
return false;
}
}

最佳答案

你可以这样做

ValueValidator<O> vldtr = valid_orInvalid == Always.VALID 
? Test.<O>newForAlwaysValid()
: Test.<O>newForAlwaysInvalid();

关于java - 在三元中使用无界泛化静态函数时如何避免未经检查的强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22898440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com