1

我需要测试 JDT/LTK 示例,为此我需要手动或以编程方式创建 eclipse 工作区和项目。

如何组织目录以便获得有效的工作区和项目对象?我的意思是,eclipse 工作区和项目有什么特别之处?

IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
// 1. The name of the project in the workspace
IProject project = root.getProject("Hello");
project.open(null /* IProgressMonitor */);

IJavaProject javaProject = JavaCore.create(project);
// 2. The name of the Type (including the namespace)
IType itype = javaProject.findType("smcho.A");
4

2 回答 2

1

下面的代码动态创建一个带有包和类的 Java 项目。也许它对你有用。

// create a project with name "TESTJDT"
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject("TESTJDT");
project.create(null);
project.open(null);

//set the Java nature
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[] { JavaCore.NATURE_ID });

//create the project
project.setDescription(description, null);
IJavaProject javaProject = JavaCore.create(project);

//set the build path
IClasspathEntry[] buildPath = {
        JavaCore.newSourceEntry(project.getFullPath().append("src")),
                JavaRuntime.getDefaultJREContainerEntry() };

javaProject.setRawClasspath(buildPath, project.getFullPath().append(
                "bin"), null);

//create folder by using resources package
IFolder folder = project.getFolder("src");
folder.create(true, true, null);

//Add folder to Java element
IPackageFragmentRoot srcFolder = javaProject
                .getPackageFragmentRoot(folder);

//create package fragment
IPackageFragment fragment = srcFolder.createPackageFragment(
        "com.programcreek", true, null);

//init code string and create compilation unit
String str = "package com.programcreek;" + "\n"
    + "public class Test  {" + "\n" + " private String name;"
    + "\n" + "}";

        ICompilationUnit cu = fragment.createCompilationUnit("Test.java", str,
                false, null);

//create a field
IType type = cu.getType("Test");

type.createField("private String age;", null, true, null);

参考:使用 Eclipse JDT 创建、访问、加载项目

于 2013-04-05T01:49:40.900 回答
1

我不确定您是否可以从正在运行的工作空间中创建新的 IWorkspace,但您应该能够创建一个目录和嵌套项目,当您重新启动 Eclipse 时可以将其用作工作空间。

另一种方法是启动 Eclipse 测试环境。有一个运行对话框,可让您指定工作区根目录。我相信,如果您足够多地探索,您可以推断出如何以编程方式启动该测试工作区(运行它)。

于 2012-12-07T23:13:21.500 回答