“否定”实例的最佳方法

本文翻译自:Best way to “negate” an instanceof

I was thinking if there exists a better/nicer way to negate an instanceof in Java. 我在想是否存在一种更好/更巧妙的方法来否定Java中的instanceof Actually, I'm doing something like: 实际上,我正在执行以下操作:

if(!(str instanceof String)) { /* do Something */ }

But I think that a "beautiful" syntax to do this should exist. 但是我认为应该存在一种“美丽”的语法。

Does anyone know if it exists, and how the syntax look like? 有谁知道它是否存在以及其语法如何?


EDIT: By beautiful, I might say something like this: 编辑:美丽,我可能会这样说:

if(str !instanceof String) { /* do Something */ } // compilation fails

#1楼

参考:https://stackoom.com/question/c32U/否定-实例的最佳方法


#2楼

ok just my two cents, use a is string method: 好的,只是我的两分钱,使用一个is字符串方法:

public static boolean isString(Object thing) {
    return thing instanceof String;
}

public void someMethod(Object thing){
    if (!isString(thing)) {
        return null;
    }
    log.debug("my thing is valid");
}

#3楼

If you find it more understandable, you can do something like this with Java 8 : 如果您觉得它更容易理解,则可以使用Java 8执行以下操作:

public static final Predicate<Object> isInstanceOfTheClass = 
    objectToTest -> objectToTest instanceof TheClass;

public static final Predicate<Object> isNotInstanceOfTheClass = 
    isInstanceOfTheClass.negate(); // or objectToTest -> !(objectToTest instanceof TheClass)

if (isNotInstanceOfTheClass.test(myObject)) {
    // do something
}

#4楼

You can achieve by doing below way.. just add a condition by adding bracket if(!(condition with instanceOf)) with the whole condition by adding ! 您可以通过以下方式实现。.只需通过添加括号if(!(condition with instanceOf))和添加整个条件的条件来添加条件! operator at the start just the way mentioned in below code snippets. 首先按照下面的代码片段中提到的方式操作运算符。

if(!(str instanceof String)) { /* do Something */ } // COMPILATION WORK

instead of 代替

if(str !instanceof String) { /* do Something */ } // COMPILATION FAIL

#5楼

No, there is no better way; 不,没有更好的办法。 yours is canonical. 你的是规范的。


#6楼

You could use the Class.isInstance method: 您可以使用Class.isInstance方法:

if(!String.class.isInstance(str)) { /* do Something */ }

... but it is still negated and pretty ugly. ...但是它仍然被否定并且非常丑陋。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值