我想在java中使用这段代码:
public <T extends View> T getView(int resId){
final View v = findViewById(resId);
if(v instanceof T) return (T)findViewById(resId);
return null;
}
但语句 v instanceof T 无法编译,错误消息为“Class或Array expect”。那么在这种情况下如何实现类型检查呢?
有些同志说因为java中的类型擦除,java不知道T是什么。但是如果java不知道T是什么,它如何实现类强制转换语句,如(T)findViewById(resId)?答案 0 :(得分:0)
请尝试以下代码:
public <T> T getView(int resId){
final View v = findViewById(resId);
if(v instanceof View)
return (T)findViewById(resId);
return null;
}