用泛型进行类型检查 [英] Type checking with generics
问题描述
class TypeChecker< T> {
boolean isGood(Object something){
//不会编译
return(something instanceof T);
//也许有用,但是太难看了!
try {
@SuppressWarnings(unchecked)
T tmp =((T)something);
} catch(ClassCastException e){
return false;
}
返回true;
$ / code $ / pre
有没有什么好的方法可以做到这一点?
具体目的与示例中的有所不同,但想法是相同的 - 检查类型T(参数)的变量是否可以保存某个对象。 p>
解决方案使用 Class#isInstance
。
class TypeChecker< T> {
私人课程< T> ofType;
TypeChecker(Class< T> ofType){
this.ofType = ofType;
boolean isGood(Object obj){
return ofType.isInstance(obj);
或者使用 Class
而不是在它周围创建一个包装对象,如果你需要的只是 isInstance
检查。
<没有其他方法可以动态地执行运行时类型检查。您必须使用 Class
。
isInstance
与 instanceof
相同的语义(除了左右翻转之外),所以
hello worldinstanceof String
String.class.isInstance(hello world)
两者都是正确的。
另外,您的'也许有效'片段,没有这个不起作用。泛型被删除,因此在运行时不会发生未经检查的转换。这就是为什么他们没有被检查。 ClassCastException将永远不会抛出。开始时使用例外来确定逻辑流程是不好的。
Here's an illustrational class:
class TypeChecker<T> {
boolean isGood(Object something) {
// won't compile
return (something instanceof T);
// maybe works, but oh so ugly!
try {
@SuppressWarnings("unchecked")
T tmp = ((T) something);
}catch(ClassCastException e) {
return false;
}
return true;
}
}
Is there any nice way to do this?
The particular purpose is a bit different than in the example, but the idea is the same - to check if a variable of type T (parameter) can hold certain object.
Use Class#isInstance
.
class TypeChecker<T> {
private Class<T> ofType;
TypeChecker(Class<T> ofType) {
this.ofType = ofType;
}
boolean isGood(Object obj) {
return ofType.isInstance(obj);
}
}
Or just use the Class
instead of making a wrapper object around it if all you need is the isInstance
check.
There is not another way to perform run-time type checking dynamically. You must use a Class
.
isInstance
has the same semantics as instanceof
(except that the left and right hand sides are flipped) so
"hello world" instanceof String
String.class.isInstance("hello world")
both are true.
Also, your 'maybe works' snippet, no that does not work. Generics are erased so unchecked casts do not happen at run-time. That is why they are unchecked. The ClassCastException will never throw. Using exceptions to determine logical flow is not good to begin with.
这篇关于用泛型进行类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!