How to cast an object to the class returned by getClass()

此生再无相见时 提交于 2019-12-12 13:17:13

问题


ProtostuffIOUtil.mergeFrom(data,o,RuntimeSchema.getSchema(o.getClass()));

How to cast Object to getClass() Class. With the above method call, I will get a compile error because the method requires that the o variable is of the same class as the o.getClass() parameter. How does one get around this?


回答1:


Class clazz = o.getClass();
ProtostuffIOUtil.mergeFrom(data, clazz.cast(o), RuntimeSchema.getSchema(clazz));



回答2:


Cast an object to the class from getClass() using the cast() method:

myObj.getClass().cast(myObj)



来源:https://stackoverflow.com/questions/7869013/how-to-cast-an-object-to-the-class-returned-by-getclass

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