为什么我收到警告:类是原始类型。对泛型类型 Class<T> 的引用应该参数化“?

2022-09-03 17:04:24

我在我的.我收到的警告如下所示ListActivity

  • Class is a raw type. References to generic type Class<T> should be parameterized

它不会产生任何问题,但我想知道为什么我会收到此警告以及如何抑制它。请参阅写在星号内的行。

public class Menu extends ListActivity {

    String classes[]={"Second","example1","example2","example3","example4"}; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(Menu.this,android.R.layout.simple_list_item_1,classes));
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        String cheese=classes[position];
        try{
        **Class ourclass= Class.forName("com.app1."+cheese);**
        Intent ourintent= new Intent(Menu.this,ourclass);
        startActivity(ourintent);
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }
    }
}

答案 1

类是通用的,如果你不关心警告,你有两个选择使用或我的偏好使用(这是一个通配符捕获)像这样@SuppressWarnings("rawtypes")<?>

Class<?> ourclass = Class.forName("com.app1."+cheese);

答案 2

您可以使用 .您还可以制作代码@SuppressWarnings("rawtypes","unchecked")

Class<?> ourclass= Class.forName("com.app1."+cheese);

以摆脱警告。现在,您不必使用 .编译器要求对所有泛型类型进行参数化@SuppressWarnings("rawtypes")


推荐