How to perform a checked cast?

若如初见. 提交于 2020-12-02 08:21:50

问题


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.

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.


回答1:


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

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

clazz.cast(test)

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

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.cast will return a value of type T, which you're fine to return.



来源:https://stackoverflow.com/questions/26022518/how-to-perform-a-checked-cast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!