gpt4 book ai didi

java - 无法将 Object 或 instanceof 转换为 true 到 IProject || Java Eclipse 插件开发

转载 作者:行者123 更新时间:2023-12-01 12:25:27 26 4
gpt4 key购买 nike

为什么我无法将对象类型数组(用于获取包资源管理器选择的 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() 返回的用户界面对象通常不是 IProjectIFileIResource 的直接实例.

要获取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
}

关于java - 无法将 Object 或 instanceof 转换为 true 到 IProject || Java Eclipse 插件开发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26381466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com