C# “is” operator alternative in Java [duplicate]

2020-08-09 06:41发布

in C# when I want to know if an object is an instance of a particular type or not, I can use "is" operator:

String foo = "hi :)"
if (foo is String) ...

how can I do it in java? (I know I can use try statement, any other way?)

标签: java casting
6条回答
啃猪蹄的小仙女
2楼-- · 2020-08-09 07:07

You'd use instanceof - that's the equivalent of is in C#. Note that there's no equivalent of as.

See the JLS section 15.20.2 for more details of instanceof, but it's basically the same as is:

// Note: no point in using instanceof if foo is declared to be String!
Object foo = "hello";
if (foo instanceof String)
{
    ...
}
查看更多
走好不送
3楼-- · 2020-08-09 07:09

instanceof is the java equivalent to the C# is operator.

查看更多
看我几分像从前
4楼-- · 2020-08-09 07:10

Java equivalent:

String foo = "hi :)"
if (foo instanceof String)
查看更多
祖国的老花朵
5楼-- · 2020-08-09 07:12

Try something like this:-

String foo = "hi :)"
if (foo instanceof String)
{
 ......
}
查看更多
forever°为你锁心
6楼-- · 2020-08-09 07:12

In java you can use "instanceof" instead of "is"

String foo = "hi :)"
if (foo instanceof String) 
查看更多
\"骚年 ilove
7楼-- · 2020-08-09 07:31
if (foo instanceof String)

I believe is what you're looking for

查看更多
登录 后发表回答