简体   繁体   English

如何在空ArrayList中测试元素类的类?

[英]How to test class for element type in an empty ArrayList?

So I have a generic ArrayList passed from parameter. 所以我有一个从参数传递的泛型ArrayList。

For example: 例如:

private <T> void testClass(ArrayList<T> data){
  if(data[0] instanceof Foo){
    //do something
  } eles if(data[0] instanceof Bar){
    //do something else
  }
}

But the arraylist does not guarantee to have an element inside and could be empty, and get(0) will raise exception. 但是arraylist并不保证内部有一个元素并且可能是空的,而get(0)将引发异常。 How can I do this? 我怎样才能做到这一点?


Edit: 编辑:

How about non-initiated generic array? 非发起的通用数组怎么样?

For example: 例如:

private <T> void testClass(T[] data){
  if(data.get(0) instanceof Foo){
    //do something
  } eles if(data.get(0) instanceof Bar){
    //do something else
  }
}

I tried T.class.getName().equals("Foo") but it does not work... 我试过T.class.getName().equals("Foo")但是它不起作用......

It's not possible to tell the difference between an empty ArrayList<String> and an ArrayList<Integer> . 无法区分空ArrayList<String>ArrayList<Integer>之间的区别。 That's quite deliberate, due to type erasure. 由于类型擦除,这是非常慎重的。 (That's because there is no difference, at runtime.) (这是因为没有什么区别,在运行时。)

Arrays are different. 数组是不同的。 At least as long as the array was actually initialized with the literal type, you can use array.getClass().getComponentType() . 至少只要使用文字类型实际初始化数组,就可以使用array.getClass().getComponentType()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM