如何在运行时同时检查 'instanceof' 和 Java 对象的通用类型?
How do I check both 'instanceof' and also the Generic type of a Java object at runtime?
如何检查使用泛型的 Java 对象的 instanceof
和 isAssignableFrom
?
如果我有这种只检查 instanceof
的方法,但我还想检查它 returns 是 Boolean
类型而不是另一种类型,我该怎么做?
public void myMethod(ObjectA<Boolean> object)
{
if ( object instanceof ObjectA ) {
// then do something
}
}
在你的例子中,instanceof
是不必要的(除非你想检查 null
,在这种情况下你应该用 ==
检查 null
) .
你的方法声明
public void myMethod(ObjectA<Boolean> object)
已经强制调用方只能传递类型为 ObjectA<Boolean>
或可分配给类型 ObjectA<Boolean>
的值。
换句话说,我写不出
这样的代码
ObjectA<Integer> notBoolean = ...;
myMethod(notBoolean);
编译器会拒绝它。
在您的方法中,由于参数的类型为 ObjectA<Boolean>
,编译器保证在运行时不会通过 ObjectA
以外的任何内容。例如,您不会以 object
持有对 Socket
或 NoSuchElementException
对象的引用而告终。
以上所有情况的例外是具有原始类型的表达式。不要使用原始类型。原因如下:
- What is a raw type and why shouldn't we use it?
对于原始类型,客户端可能会编写
ObjectA<Integer> notBoolean = ...
ObjectA raw = notBoolean;
myMethod(raw);
并且编译器会放弃通用类型检查并允许调用(编译器会删除该调用上下文中的通用用法)。
你的代码可能会在运行时失败,并在尝试
时出现 ClassCastException
public void myMethod(ObjectA<Boolean> object)
{
Boolean ref = object.get(); // ClassCastException
// returns an `Integer` and attempts to assign it to a `Boolean` variable
}
您的 object
仍将保留对 ObjectA
实例的引用,但无论它可能包装什么,都不再一定是 Boolean
(我假设 ObjectA
是 Boolean
值的某种包装器)。
这个 ClassCastException
将或多或少等同于你本来可以扔的东西。
我不会专门针对这种原始用法进行检查。
如何检查使用泛型的 Java 对象的 instanceof
和 isAssignableFrom
?
如果我有这种只检查 instanceof
的方法,但我还想检查它 returns 是 Boolean
类型而不是另一种类型,我该怎么做?
public void myMethod(ObjectA<Boolean> object)
{
if ( object instanceof ObjectA ) {
// then do something
}
}
在你的例子中,instanceof
是不必要的(除非你想检查 null
,在这种情况下你应该用 ==
检查 null
) .
你的方法声明
public void myMethod(ObjectA<Boolean> object)
已经强制调用方只能传递类型为 ObjectA<Boolean>
或可分配给类型 ObjectA<Boolean>
的值。
换句话说,我写不出
这样的代码ObjectA<Integer> notBoolean = ...;
myMethod(notBoolean);
编译器会拒绝它。
在您的方法中,由于参数的类型为 ObjectA<Boolean>
,编译器保证在运行时不会通过 ObjectA
以外的任何内容。例如,您不会以 object
持有对 Socket
或 NoSuchElementException
对象的引用而告终。
以上所有情况的例外是具有原始类型的表达式。不要使用原始类型。原因如下:
- What is a raw type and why shouldn't we use it?
对于原始类型,客户端可能会编写
ObjectA<Integer> notBoolean = ...
ObjectA raw = notBoolean;
myMethod(raw);
并且编译器会放弃通用类型检查并允许调用(编译器会删除该调用上下文中的通用用法)。
你的代码可能会在运行时失败,并在尝试
时出现ClassCastException
public void myMethod(ObjectA<Boolean> object)
{
Boolean ref = object.get(); // ClassCastException
// returns an `Integer` and attempts to assign it to a `Boolean` variable
}
您的 object
仍将保留对 ObjectA
实例的引用,但无论它可能包装什么,都不再一定是 Boolean
(我假设 ObjectA
是 Boolean
值的某种包装器)。
这个 ClassCastException
将或多或少等同于你本来可以扔的东西。
我不会专门针对这种原始用法进行检查。