Home  >  Q&A  >  body text

java - 如何写一个intellij-idea插件,实现编译时修改源代码的目的

比如下面这段Java源码:

String pcName = "$local_pc_name$";
System.out.println(pcName);

我希望IDEA编译后运行,输出的是具体的电脑名,也就是说,在哪台机器编译,就输出哪台。
比如我是在a-pc这台电脑上编译的,就输出显示a-pc

这个怎么写插件实现呢?

PS:
1、源码不修改,也就是保证另一台电脑编译时也有"$local_pc_name$"这个标记;
2、我想写个IDEA插件,在编译时自动处理这样的字符串。

还烦请大神出手相助一二。

补充:电脑名这个只是我举了个栗子,我的目的是编译时替换特定字符串,而且源码不变。
也感谢已经回复的两位朋友出谋划策。

巴扎黑巴扎黑2743 days ago779

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-18 10:55:26

    I hope that after IDEA is compiled and run, the output will be the specific computer name. In other words, whichever machine it is compiled on will be the output.

    Try this

    import java.net.InetAddress;
    import java.net.UnknownHostException;
    
    String hostname = "Unknown";
    
    try
    {
        InetAddress addr;
        addr = InetAddress.getLocalHost();
        hostname = addr.getHostName();
    }
    catch (UnknownHostException ex)
    {
        System.out.println("Hostname can not be resolved");
    }

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:55:26

    Set via environment variables

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:55:26

    AbstractProcessor
    Annotation processors should be used instead of plugins.

    reply
    0
  • Cancelreply