获取java.util.Arrays $ ArrayList的类 [英] Get the class of java.util.Arrays$ArrayList
问题描述
我怎么知道java.util.Arrays$ArrayList
的实例.我已经尝试过此代码段,但它根本不起作用:
How can I know the instance of java.util.Arrays$ArrayList
. I've tried this code snippet but it does not work at all :
if (myList instanceof Arrays) {
//Do something here.
}
我已经将对象类类型与ArrayList进行了比较,但我遇到了同样的问题.但是当我检查对象时,classType是一个:
I have compared the object classtype with ArrayList and I had the same issue. But while I was inspecting the object, the classType was a :
class java.util.Arrays$ArrayList
以下条件语句是我找到的唯一解决方案:
The conditional statement below was the only solution I found:
else if (myList.getClass().toString().equals("class java.util.Arrays$ArrayList")) {
//do something here
}
但是我认为通过使用instanceof控制对象类型将是一个很好的解决方案.
but I think that controlling the object type by using instanceof would be a great solution.
我的问题是:java.util.Arrays$ArrayList
的类类型是什么,所以我可以使用 instanceof 作为控件.
My question is : what is the classType of java.util.Arrays$ArrayList
, so I can use instanceof for my control.
预先感谢
奥马尔.
推荐答案
java.util.Arrays$ArrayList
是Arrays
的私有内部类,由Arrays.asList
方法返回.
java.util.Arrays$ArrayList
is a private inner class of Arrays
, returned by the Arrays.asList
method.
由于它是私有类,因此无法以与instanceof
运算符一起使用的方式来访问该类.您可以使用反射来执行此检查:
Since it's a private class there is no way to get access to the class in a way that it can be used with the instanceof
operator. You can do this check using reflection however:
Class<?> clazz = Class.forName("java.util.Arrays$ArrayList");
// ...
clazz.isAssignableFrom(myList)
但是我不建议您这样做. 对接口进行编程是一个好习惯.在这种情况下, List
接口定义了对象的行为. 对象的实际类别无关紧要.
But I do not recommend doing that. It's a good practice to program against an interface. In this case the List
interface defines the behavior of the object. The actual class of the object shouldn't matter.
这篇关于获取java.util.Arrays $ ArrayList的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!