How to convert between an Object[] and an interface (IProject[]) in Java?

此生再无相见时 提交于 2019-12-11 05:10:31

问题


I have an Object[] in Java and want to convert it to IProject[], which is a Java interface (org.eclipse.core.resources.IProject), in order to write a plugin for eclipse.

Is this possible?

Regards


回答1:


You can't convert the array itself - arrays know the type of their slots, so you can't just cast an instance of Object[] to an expression of type IProject[], even if the array happens to contain only instances of IProject (unless you happen to have a variable of type Object[] which actually points to an instance of IProject[]).

Instead, you'll need to make a new array with the same contents:

Object[] objects;
IProject[] projects = new IProject[objects.length];
System.arraycopy(objects, 0, projects, 0, objects.length);

Array stores are dynamically type-checked, so if your Object[] contains any objects which are not instances of IProject, you'll get an ArrayStoreException.




回答2:


are the Objects in Object[] instances of IProject ?

see casting Object array to Integer array error



来源:https://stackoverflow.com/questions/7256498/how-to-convert-between-an-object-and-an-interface-iproject-in-java

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