如何动态投射东西?

时间:2017-10-10 22:17:30

标签: java

我想通过调用类似的东西动态地投射东西:

Object genericObject = new MyObject();
MyObject myObject = getObject(genericObject, MyObject.class);

public static final T getObject(Object object, Class<T> clazz){
    if(isInstance(object, clazz)){
        return object;
    }
    return null;
}

如何修复getObject()方法以使其有效?

1 个答案:

答案 0 :(得分:2)

您可以使用Class#cast

public static final <T> T getObject(Object object, Class<T> clazz) {
    if(clazz.isInstance(object)) {
        return clazz.cast(object);
    }
    return null;
}