I created a NewFile-Wizard for a plugin in eclipse. I would like to place the new file exactly where the forwarded IStructuredSelection
points. My problem is that I only know how to handle instances of IResource
but not other resources:
public class WizardNewShader extends Wizard implements INewWizard {
... implementations omitted...
IContainer fileLocation;
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
Object s = selection.getFirstElement();
if (s instanceof IResource) {
if (s instanceof IContainer) {
fileLocation = (IContainer) s;
} else {
fileLocation = ((IResource) s).getParent();
}
} else {
System.out.println("what shall we do with a " + s.getClass() + "?");
}
}
}
Some container types work nicely, because they are instances of IResource
, but others are not recognized:
what shall we do with a class org.eclipse.jdt.internal.core.PackageFragment?
what shall we do with a class org.eclipse.jdt.internal.core.JavaProject?
what shall we do with a class org.eclipse.cdt.internal.core.model.SourceRoot?
Is there any other way to handle theses resources than a big instanceof switch, that contains different code for every resource type?
User interface objects generally don't implement the IResource
interface directly, instead they provide an 'adapter'. In some cases they implement IAdaptable
and you can get the resource using:
IAdaptable adaptable = (IAdaptable)s;
IResource resource = (IResource)adaptable.getAdapter(IResource.class);
In other cases the 'adapter manager' is used:
IResource resource = (IResource)Platform.getAdapterManager().getAdapter(s, IResource.class);
The adapter manager will generally deal with most cases.