为什么不能将对象类型的数组(用于获取选择包浏览器的Eclipse框架方法返回)的内容转换为IProject? instanceof返回false,并且不检查就强制转换会导致异常。但是调试器将Object []数组的内容显示为具有所有实例变量和IProject类型的所有内容:
private List<IProject> getValidSelectedProjects(IWorkbenchWindow window) {
final ISelectionService service = window.getSelectionService();
final IStructuredSelection structured = (IStructuredSelection) service.getSelection("org.eclipse.jdt.ui.PackageExplorer");
if (structured == null){
return null;
} else {
final Object[] selectedProjects = structured.toArray();
ArrayList<IProject> validatedProjects = new ArrayList<IProject>();
for (final Object projectObj : selectedProjects){
if (projectObj instanceof IProject){
IProject project = (IProject) projectObj;
//do something
}
//rest of the method; returning list of validated projects
我也试过
How to convert between an Object[] and an interface (IProject[]) in Java?
但是我在这行得到一个异常:
System.arraycopy(objectarray, 0, projectarray, 0, objectarray.length);
最佳答案
getSelection()
返回的用户界面对象通常不是IProject
,IFile
或IResource
的直接实例。
要获取IProject
...,请使用IAdapterManager
:
IProject project = (IProject)Platform.getAdapterManager().getAdapter(projectObj, IProject.class);
有时,对象不提供直接连接到
IProject
的适配器,因此请尝试更通用的IResource
:IResource resource = (IResource)Platform.getAdapterManager().adapt(projectObj, IResource.class);
if (resource instanceof IProject)
{
IProject project = (IProject)resource;
... your code
}