本文翻译自: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. ...但是它仍然被否定并且非常丑陋。
36

被折叠的 条评论
为什么被折叠?



