获取 java.util.Arrays$ArrayList 的类 [英] Get the class of java.util.Arrays$ArrayList

查看:42
本文介绍了获取 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 的 classType 是什么,所以我可以使用 instanceof 作为我的控件.

My question is : what is the classType of java.util.Arrays$ArrayList, so I can use instanceof for my control.

提前致谢,

奥马尔.

推荐答案

java.util.Arrays$ArrayListArrays 的一个私有内部类code>,由 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆