怎么看一个对象是否是不使用反射阵列? [英] How to see if an object is an array without using reflection?
问题描述
我如何在Java中一个对象是否是不使用反射阵列?
以及如何通过我的所有项目不重复使用反射?
我使用谷歌GWT,所以我不能使用反射:(
我很想实现以下方法不使用refelection:
私人布尔IsArray的(最终obj对象){
// ?? ..
}私人字符串的toString(最终目标ArrayObject的){
// ?? ..
}
BTW:我也不希望使用JavaScript,这样我可以在非GWT环境中使用它
您可以使用的instanceof
。
JLS 15.20.2类型比较运算符的instanceof
RelationalEx pression:
RelationalEx pression的instanceof引用类型
在运行时,在
的instanceof
运算符的结果是真正
如果该值的 RelationalEx pression 的不空
和参考可转换为的引用类型的没有抚养ClassCastException异常
。否则,结果是假
。
块引用>这意味着你可以做这样的事情:
对象o = INT新[] {1,2};
的System.out.println(邻的instanceof INT []); //输出真您不得不检查,如果对象是一个
的instanceof布尔[]
,字节[]
,短[]
,的char []
,INT []
,长[]
,浮动[]
,双[]
或对象[]
,如果你想检测所有的数组类型。此外,一个
INT [] []
是的instanceof对象[]
,所以这取决于你怎么想处理嵌套数组,它可以变得复杂。对于
的toString
的java.util.Arrays中的
有一个的toString(INT [])
和其他重载可以使用。它还具有deepToString(对象[])
的嵌套数组。公共字符串的toString(对象ARR){
如果(ARR的instanceof INT []){
返回Arrays.toString((INT [])ARR);
信息} else // ...
}这将是非常重复性(但即使<一个href=\"http://www.google.com/$c$csearch/p?hl=en#av_p04Hv9fs/src/share/classes/java/util/Arrays.java&l=478\"><$c$c>java.util.Arrays$c$c>很重复),但是这是在Java中使用数组的方式。
另请参见
How can I see in Java if an Object is an array without using reflection? And how can I iterate through all items without using reflection?
I use Google GWT so I am not allowed to use reflection :(
I would love to implement the following methods without using refelection:
private boolean isArray(final Object obj) { //??.. } private String toString(final Object arrayObject) { //??.. }
BTW: neither do I want to use JavaScript such that I can use it in non-GWT environments.
解决方案You can use
instanceof
.JLS 15.20.2 Type Comparison Operator
instanceof
RelationalExpression: RelationalExpression instanceof ReferenceType
At run time, the result of the
instanceof
operator istrue
if the value of the RelationalExpression is notnull
and the reference could be cast to the ReferenceType without raising aClassCastException
. Otherwise the result isfalse
.That means you can do something like this:
Object o = new int[] { 1,2 }; System.out.println(o instanceof int[]); // prints "true"
You'd have to check if the object is an
instanceof boolean[]
,byte[]
,short[]
,char[]
,int[]
,long[]
,float[]
,double[]
, orObject[]
, if you want to detect all array types.Also, an
int[][]
is aninstanceof Object[]
, so depending on how you want to handle nested arrays, it can get complicated.For the
toString
,java.util.Arrays
has atoString(int[])
and other overloads you can use. It also hasdeepToString(Object[])
for nested arrays.public String toString(Object arr) { if (arr instanceof int[]) { return Arrays.toString((int[]) arr); } else //... }
It's going to be very repetitive (but even
java.util.Arrays
is very repetitive), but that's the way it is in Java with arrays.See also
- Managing highly repetitive code and documentation in Java
- Java Arrays.equals() returns false for two dimensional arrays.
这篇关于怎么看一个对象是否是不使用反射阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!