使用NewInstance进行投射

Mik*_*ail 0 java casting classcastexception

我需要从一种类型转换为另一种类型.谷歌搜索但坚持.说我要投initObjectCasted类.

Object objInstance = initObject.getClass().newInstance();
                    Casted str=(Casted)objInstance;
Run Code Online (Sandbox Code Playgroud)

为什么会这样ClassCastException

dis*_*ned 6

转换要求Class Casted必须是Class 的子类或子接口initObject.例如:

List<String> list = new ArrayList<String>();
ArrayList<String> castedList = (ArrayList<String>) list; //works
Integer int = (Integer) list; // throws ClassCastException
Run Code Online (Sandbox Code Playgroud)

cast的替代方法可以是将转换相关对象的辅助方法.这样的例子是Collections.toArray方法.

通常不鼓励使用转换,因为您基本上告诉编译器您知道转换对象是什么类型,当然您可能是错的.