IJavaProject jproject = JavaCore.create(project);
try {
IType type = jproject.findType(object.getClassName());
if (type!=null) {
JavaUI.openInEditor(type); //支持打开源文件和类文件
} else {
NewClassWizardPage page = new NewClassWizardPage();
page.init(new StructuredSelection(project));
// 其中clsName是要新建的java文件的全名(包名+类名)
String clsName = object.getClassName();
if (clsName.length() > 0) {
JavaProject jProject = (JavaProject) JavaCore.create(project.getProject());
// 获取源代码路径
String srcPath = project.getProject().getFullPath().toOSString() + "//src";
IPackageFragmentRoot root = jProject.findPackageFragmentRoot(Path.fromOSString(srcPath));
// 设置包路径
if (clsName.lastIndexOf(".") > 0) {
String pkgName = clsName.substring(0, clsName.lastIndexOf("."));
page.setPackageFragment(root.getPackageFragment(pkgName), true);
}
// 设置文件名
page.setTypeName(clsName.substring(clsName.lastIndexOf('.') + 1), true);
}
NewClassCreationWizard createJavaWizard = new NewClassCreationWizard(page, true);
createJavaWizard.init(PlatformUI.getWorkbench(), new StructuredSelection(project));
WizardDialog dialog = new WizardDialog(getSite().getShell(), createJavaWizard);
if (dialog.open() == WizardDialog.OK) {
object.setClassName(((IType) createJavaWizard.getCreatedElement()).getFullyQualifiedName());
}
}
} catch (JavaModelException e1) {
e1.printStackTrace();
} catch (PartInitException e2) {
e2.printStackTrace();
}