我想通过调用类似的东西动态地投射东西:
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()
方法以使其有效?
答案 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;
}