我想知道是否有一种方法(以编程方式)来检查代码是否在 Eclipse、IntelliJ、任何其他编辑器中运行或从命令行(控制台)运行。
我正在考虑使用 System.getProperty() 但是否有任何属性表明这一点?
IntelliJ IDEA
运行的。
public static boolean runningFromIntelliJ()
{
String classPath = System.getProperty("java.class.path");
return classPath.contains("idea_rt.jar");
}
它已经在
Linux
、Mac OS X
和 Windows
上进行了测试,因此它应该是独立于平台的。
没有可靠的方法可以做到这一点。 IDE 本身将使用系统上安装的 JRE/JDK 或随 IDE 一起提供的 JRE/JDK。 SDK/JVM 中没有任何内容专门将自身标识为从 IDE 中运行。
如果您需要在程序中识别这一点,请在从 IDE 运行代码时通过 -D 标志传递系统属性。此属性的存在(或不存在)可用于确定代码从何处运行。
如果没有自定义运行参数,就没有可靠的方法来做到这一点,但是!
这比检查
idea_rt.jar
更可靠:
public static void main(String[] args) {
boolean intellij = false;
try {
intellij = Main.class.getClassLoader().loadClass("com.intellij.rt.execution.application.AppMainV2") != null;
} catch (ClassNotFoundException e) {
}
System.out.println(intellij);
}
来源:https://intellij-support.jetbrains.com/hc/en-us/community/posts/360000015340/comments/360000017399
仅当您不使用运行/调试配置中的“缩短命令行”选项之一时,这才有效。由于我们需要缩短命令行(类路径变得太长),我现在正在使用
public static boolean runningFromIntelliJ()
{
return System.getProperty("idea.test.cyclic.buffer.size") != null;
}
IntelliJ 在运行测试时设置该属性。
在 Mac 上使用 Eclipse 和 IntelliJ 进行测试:
String xpcsce = System.getenv("XPC_SERVICE_NAME") );
使用终端将返回“0”,使用 Eclipse 将返回“application.org.eclipse.platform.ide...”,使用 IntelliJ 将返回“application.com.jetbrains.intellij.ie-EAP...”...
但 XPC 服务是 MacOS 特定功能,因此不适用于任何其他平台。
这里有一些方法:
private static boolean checkIntelliJIDEA() {
try {
URL ideDetectorClassLocation = IdeDetector.class.getProtectionDomain().getCodeSource().getLocation();
File ideDetectorClassFile = new File(ideDetectorClassLocation.toURI());
return ideDetectorClassFile.isDirectory();
} catch (URISyntaxException e) {
System.err.println("Error determining if the application is running in an IDE: " + e.getMessage());
}
String ideaLaunchProperty = System.getProperty("idea.launcher.port");
String ideaRunConfigProperty = System.getProperty("idea.run.configuration");
String classpath = System.getProperty("java.class.path");
if(classpath.contains("idea_rt.jar")) return true;
if(ideaLaunchProperty != null) return true;
if(ideaRunConfigProperty != null) return true;
if(ideaRunConfigProperty != null) return true;
try {
Class.forName("com.intellij.rt.execution.application.AppMainV2");
Class.forName("com.intellij.rt.execution.application.AppMain");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
我最近遇到了在 IntelliJ 中运行时失败的测试(我还无法解决原因,但可能是由于线程)。我能够使用单个测试用例注释来解决此问题,该注释测试仅 IntelliJ 设置的环境变量。
我知道这是为 Junit 排除而编写的,但希望将其作为对需求的可能的部分答案进行分享,因为我花了一些时间寻找解决方案,而这个讨论是我能找到的最接近的讨论。
@DisabledIfEnvironmentVariable(named = "IJ_RESTARTER_LOG", matches = ".*", disabledReason = "Fails when all tests run in IntelliJ")