java通用方法警告“;“未经检查的铸件”;

java通用方法警告“;“未经检查的铸件”;,java,android,generics,findviewbyid,Java,Android,Generics,Findviewbyid,我编写了一个方法来替换View.findViewById(int-id),但得到了一个警告: 这个方法有什么问题吗?或者如何避免它?我相信这就是警告的原因:Java允许向下转换,即,将X类型的对象转换为X的子类。但是,这需要在运行时进行检查。例如: Object x1 = <... something that returns an object that may be a String ...>; String x2 = (String)x1; 如果findViewById找到

我编写了一个方法来替换
View.findViewById(int-id)
,但得到了一个警告:


这个方法有什么问题吗?或者如何避免它?

我相信这就是警告的原因:Java允许向下转换,即,将X类型的对象转换为X的子类。但是,这需要在运行时进行检查。例如:

Object x1 = <... something that returns an object that may be a String ...>;
String x2 = (String)x1;
如果
findViewById
找到的对象不是真正的
View2
,您将得到
ClassCastException
。但是:

View v = YourClass.<View2>find(x, id);
假设
findViewById
返回其他视图。当我尝试这样做时,我认为它不会抛出异常,因为另一个视图也会有
toString()
(与所有
对象一样)。但这确实引发了
ClassCastException

我不知道是否有一个好方法来修复它。一种可能是在
find
中添加第三个参数,以表示
T
的类别,并使用其
cast
方法:

public static <T extends View> T find(View view, int id, Class<T> theClass) {
    return theClass.cast(view.findViewById(id));
}

View v = YourClass.find(x, id, View2.class);
publicstatict-find(视图、int-id、类){
返回class.cast(view.findViewById(id));
}
View v=YourClass.find(x,id,View2.class);
这是可行的——如果
findViewById
返回错误的类,它会从
cast()
方法抛出异常。但是,在每次使用中添加第三个参数可能并不吸引人,尽管它可能允许您从调用中删除显式泛型类型参数

我认为在这种情况下,可以忽略警告,并使用
@SuppressWarnings(“unchecked”)
来阻止警告显示,如果您认为有时当
findViewById
返回错误类型的视图时,程序可能会继续而不是抛出异常,那么就可以了

(免责声明:我的测试是使用Java 8进行的。我没有使用任何在Java 7中无效的东西。但是如果Android仍然没有完全实现Java 7,我写的一些东西可能是错误的。)

String s = YourClass.<View2>find(x, id).toString();
public static <T extends View> T find(View view, int id, Class<T> theClass) {
    return theClass.cast(view.findViewById(id));
}

View v = YourClass.find(x, id, View2.class);