使用代码run或者debug某个test.java的main方法
package com.tmall.testgen.launch;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
/**
*
* @author liuzx
*
*/
public class LaunchMainClass {
public static void test() {
String projectName = "testgen";
String mainClass = "com.test.Test";
launch(projectName, mainClass);
}
public static void launch(String projectName, String mainClass) {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IProject project = workspace.getRoot().getProject(projectName);
IJavaProject javaProject = JavaCore.create(project);
String name = mainClass;
try {
launch(javaProject, name, mainClass);
} catch (CoreException e) {
e.printStackTrace();
}
}
private static void launch(IJavaProject proj, String name, String mainClass)
throws CoreException {
try {
ILaunchManager manager = DebugPlugin.getDefault()
.getLaunchManager();
//java application配置类型
ILaunchConfigurationType type = manager
.getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION);
ILaunchConfiguration config = null;
ILaunchConfiguration[] configurations = manager
.getLaunchConfigurations(type);
//查看 是否已经存在
for (int i = 0; i < configurations.length; i++) {
if (configurations[i].getName().equals(name))
config = configurations[i];
}
// else create a new one
if (config == null) {
ILaunchConfigurationWorkingCopy wc = type.newInstance(null,
name);
wc.setAttribute(
IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
proj.getProject().getName());
// current directory should be the project root
wc.setAttribute(
IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY,
proj.getProject().getLocation().toString());
// use the suplied args
wc.setAttribute(
IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
mainClass);
// wc.setAttribute(
// IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
// args);
// saves the new config path=\.metadata\.plugins\org.eclipse.debug.core\.launches\name.launch
config = wc.doSave();
}
config.launch(ILaunchManager.DEBUG_MODE, null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
参考:
http://www.blogjava.net/adolf-zhang/archive/2007/11/26/dengues_04.html
http://www.blogjava.net/jame-liu/articles/15805.html
http://www.eclipse.org/articles/Article-Java-launch/launching-java.html