Type checking with generics

淺唱寂寞╮ 提交于 2020-01-14 15:01:11

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/22733401/type-checking-with-generics

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!