问题描述
我在Java中有一个Object [],并希望将它转换为IProject [],这是一个Java接口(org.eclipse.core.resources.IProject),以便为eclipse编写一个插件。这是可能吗?
关心
您不能转换数组本身 - 数组知道其插槽的类型,因此您不能只投掷一个 Object []
到 IProject []
的表达式,即使数组恰好只包含 IProject
的实例(除非你发生要有一个类型为 Object []
的变量,它实际上指向一个 IProject []
的实例)。
相反,您需要使用相同的内容创建一个新数组:
Object [] objects;
IProject [] projects = new IProject [objects.length];
System.arraycopy(objects,0,projects,0,objects.length);
数组存储是动态类型检查的,所以如果你的 Object []
包含不是 IProject
的实例的任何对象,您将得到一个 ArrayStoreException
。
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
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
.
这篇关于如何在Java中的Object []和接口(IProject [])之间进行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!