java 如何进行检查演员表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26022518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:08:56  来源:igfitidea点击:

How to perform a checked cast?

javagenericscasting

提问by AllenKll

I am new to Generics and am having an issue.

我是泛型的新手,遇到了一个问题。

Consider the following code:

考虑以下代码:

public class A {}
public class B extends A {}

public <T extends A> T getB()
{
    A test = new B();
    Class<B> clazz = B.class;
    if (clazz.isInstance(test))
    {
        return (T)test;
    }
    return null;
}

This generates an Unchecked cast warning. on the return (T)test;line. but clearly I am checking the type with the if (clazz.isInstance(test))line.

这会生成 Unchecked cast 警告。就return (T)test;行了。但显然我正在检查if (clazz.isInstance(test))线路的类型。

Is there a way to do a "checked cast"?

有没有办法做一个“检查演员”?

I'm not looking to just suppress the warning but actually implement a checked cast. Unfortunately I can't find information on how to perform a checked cast.

我不希望只是抑制警告,而是实际实施已检查的强制转换。不幸的是,我找不到有关如何执行检查转换的信息。

回答by Jon Skeet

Is there a way to do a "checked cast"?

有没有办法做一个“检查演员”?

Sure, although it's important to note that it doesn't reallyhelp you here, because your method is hard-coded to use Bin a few places. You can perform the cast with:

当然,尽管重要的是要注意它在这里并没有真正帮助您,因为您的方法是硬编码的,可以B在一些地方使用。您可以通过以下方式执行演员表:

clazz.cast(test)

... but that will cast to B, not T. In particular, suppose I ran:

...但这将转换为B,而不是T。特别是,假设我跑了:

public class C extends A {}

...

C c = foo.<C>getB();

How would you expect that to work?

你希望它如何工作?

You might want to change your code to something like:

您可能希望将代码更改为以下内容:

public <T extends A> T getB(Class<T> clazz)
{
    A test = // get A from somewhere
    return clazz.isInstance(test) ? clazz.cast(test) : null;
}

Then that's fine, because clazz.castwill return a value of type T, which you're fine to return.

那很好,因为clazz.cast将返回一个 type 值T,您可以返回它。