Intellij Idea 检查Java代码是否从IntelliJ、Eclipse等或命令行运行

uqjltbpv  于 2023-04-19  发布在  Java
关注(0)|答案(5)|浏览(218)

我想知道是否有一种方法(编程)来检查代码是否在Eclipse,IntelliJ,任何其他编辑器中运行或从命令行(控制台)运行。
我想使用System.getProperty(),但是有没有任何属性可以表明这一点呢?

xghobddn

xghobddn1#

下面的代码可以检测您的代码是否从IntelliJ IDEA运行。

public static boolean runningFromIntelliJ()
{
    String classPath = System.getProperty("java.class.path");
    return classPath.contains("idea_rt.jar");
}

经过测试,它可以在LinuxMac OS XWindows上运行,因此它应该是平台无关的。

taor4pac

taor4pac2#

没有可靠的方法来做到这一点。IDE本身将使用安装在您的系统上的JRE / JDK或IDE附带的JRE / JDK。SDK / JVM中没有任何内容专门标识自己是从IDE中运行的。
如果需要在程序中标识此属性,请在从IDE运行代码时通过-D标志传递系统属性。此属性的存在(或不存在)可用于确定代码的运行位置。

gdx19jrr

gdx19jrr3#

如果没有自定义运行参数,没有可靠的方法可以做到这一点,但是!
这比检查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

ecfsfe2w

ecfsfe2w4#

只有当你不使用Run/Debug配置中的“Shorten command line”选项时,这才有效。

public static boolean runningFromIntelliJ()
{
    return System.getProperty("idea.test.cyclic.buffer.size") != null;
}

IntelliJ在运行测试时设置该属性。

oxosxuxt

oxosxuxt5#

在使用Eclipse和IntelliJ的Mac上测试:
String xpcsce = System.getenv("XPC_SERVICE_NAME") );
将返回“0”与终端,“application.org.eclipse.platform.ide....”与Eclipse和“application.com.jetbrains.intellij.ie-EAP....”与IntelliJ...
但XPC服务是MacOS特有的功能,因此在任何其他平台上都无法使用。

相关问题