在Java中,我可以在instanceof表达式中使用基本类型文字或类型变量吗? [英] In Java, can I use a primitive type literal or type variable in an instanceof expression?
问题描述
我可以在 instanceof
表达式中使用基本类型文字或类型变量吗?
Can I use a primitive type literal or type variable in an instanceof
expression?
class MyClass<T> {
{
boolean b1 = null instanceof T; // T erasure -> Object should be used
boolean b2 = 2 instanceof Integer; // Incompatible operands
}
我收到编译错误。有没有办法绕过这些错误并在 instanceof
表达式中使用原始类型的文字/类型变量?
I'm getting compilation errors. Is there any way to circumvent these errors and use a primitive type literal/type variable in an instanceof
expression?
基本上,我想要放心,不,我永远无法做到。
Basically, I want to be reassured that no, I will never be able to do that.
推荐答案
不,因为类型擦除。 MyClass< T>
的实例实际上并不知道 T
是什么。
Nope, because of type erasure. An instance of MyClass<T>
doesn't actually know what T
is.
您需要有一个 Class< T>
的实例。然后你可以使用 isInstance
方法。一种方法是在构造函数中指定它:
You need to have an instance of Class<T>
. Then you can use the isInstance
method. One way of doing that is to specify it in the constructor:
class MyClass<T>
{
private Class<T> clazz;
MyClass(Class<T> clazz)
{
this.clazz = clazz;
}
// Now you can use clazz to check for instances, create new instances ect.
}
对于第二个,问题是第一个操作数,而不是第二个操作数。原始值本身不是 Integer
的实例;盒装版本是:
For the second one, the problem is the first operand, not the second. The primitive value itself isn't an instance of Integer
; the boxed version is:
Object obj = 2;
boolean b2 = obj instanceof Integer;
每当你有一个真正的原始价值时,你就会知道这种类型类型检查没有多大意义。
Whenever you've got a genuine primitive value, you'll already know the type so making a dynamic type check doesn't make much sense.
这篇关于在Java中,我可以在instanceof表达式中使用基本类型文字或类型变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!