java java中如何判断一个对象是字符串还是字符串数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4244106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:28:55  来源:igfitidea点击:

How to check whether an Object is String or String Array in java?

java

提问by Shashank T

A method is returning a Objector Object[]of type Stringbut if I am casting with String[], it is giving class cast exception when it contains single string. How can i resolve this?

一个方法正在返回一个ObjectorObject[]类型,String但是如果我使用 进行转换String[],它会在包含单个字符串时给出类转换异常。我该如何解决这个问题?

Is there any way to check whether it contains Stringor String[]?

有没有办法检查它是否包含StringString[]

回答by Jon Skeet

Sure, use the instanceofoperator:

当然,使用instanceof运算符

if (x instanceof String) {
  ...
}

if (x instanceof String[]) {
  ...
}

etc. It's not ideal to have to do this, mind you... is there any way you could redesign your API to avoid this?

等等。必须这样做并不理想,请注意……有什么方法可以重新设计 API 以避免这种情况?

回答by Michael Borgwardt

Rewrite the method to always return String[], even when there's only a single one.

重写方法以始终 return String[],即使只有一个。

Better yet, have it return List<String>and use Collections.singletonList()for the single-element case.

更好的是,让它返回List<String>Collections.singletonList()用于单元素情况。