【问题标题】:How to automatically initialize a static variable that call InetAddress.getLocalHost()?如何自动初始化调用 InetAddress.getLocalHost() 的静态变量?
【发布时间】:2013-12-03 11:21:09
【问题描述】:

按照这个简短的教程http://www.rgagnon.com/javadetails/java-0095.html 我正在尝试获取我的客户端IP 地址

与本教程的唯一区别是我希望将我的 IP 地址放在 静态变量 中,因此我按以下方式进行:

private static InetAddress thisIp = InetAddress.getLocalHost();

但是 Eclipse 给了我以下错误信息:Unhandled exception type UnknownHostException

所以,我认为问题在于我无法调用此代码:

InetAddress.getLocalHost();

到一个静态变量中,但我必须首先声明该静态变量,然后将其初始化到每个使用它的方法中。

我需要它进入 JUnit 测试的问题,这是非常糟糕的,每次都将它初始化到所有 @test 方法中!!!

那么,我能做些什么来避免在每个测试方法中初始化它?还有其他方法可以只初始化一次吗?我可以创建一个初始化方法,当我运行我的测试类时,它会在开始时自动执行?怎么样?

Tnx

安德烈亚

【问题讨论】:

    标签: java junit


    【解决方案1】:

    尝试在静态块上初始化,

    private static InetAddress thisIp;
    
    static{
        try {
            thisIp  = InetAddress.getLocalHost();
        } catch (UnknownHostException ex) {
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用静态初始化块:

      class YourClass {
      
          private static InetAddress thisIp;
      
          static {
            try {
              thisIp = InetAddress.getLocalHost();
            } catch(Exception ex) {
              Logger.log(ex);
            } finally {
              ...
            }
          }
         ...
      }
      

      这个块可以在类中的任何位置,在任何方法之外。

      【讨论】:

      • 嗯,这是什么?怎么样?
      猜你喜欢
      • 1970-01-01
      • 2011-08-22
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 2017-05-13
      • 2010-12-11
      相关资源
      最近更新 更多