PMD规则DataflowAnomalyAnalysis奇怪

时间:2009-07-19 19:16:13

标签: java pmd

我有以下JUnit测试:

@Test
public void testRunLocalhost() throws IOException, InterruptedException {
    // Start an AnnouncerThread
    final AnnouncerThread announcer = new AnnouncerThread();
    announcer.start();

    // Create the socket and listen on the right port.
    final DatagramSocket socket = new DatagramSocket();
    assert(socket != null);

    // Create a packet to send.
    final DatagramPacket packet = new DatagramPacket(new byte[0], 0, InetAddress.getByName(AnnouncerThread.GROUP), AnnouncerThread.PORT);
    assert(packet != null);

    // Send the packet.
    socket.send(packet);

    // Listen for the IP from the server.
    final DatagramPacket receivedPacket = new DatagramPacket(new byte[256], 256);
    socket.setSoTimeout(2000); // Only wait 2 seconds.
    socket.receive(receivedPacket);
    socket.close();

    // Get localhost's address.
    final InetAddress localhost = InetAddress.getLocalHost();
    assert(localhost != null);

    // Compare the receive IP to the localhost IP.
    final String receivedIP = new String(receivedPacket.getData());
    if (!receivedIP.startsWith(localhost.getHostAddress())) {
        fail("Received IP: '" + receivedIP + "' not the same as localhost: '" + localhost.getHostAddress() + "'");
    }

    announcer.shutdown();
    announcer.join();
}

PMD发出以下违规行为:

Found 'UR'-anomaly for variable 'socket' (lines '36'-'36').
Found 'UR'-anomaly for variable 'localhost' (lines '36'-'36').
Found 'UR'-anomaly for variable 'packet' (lines '36'-'36').

我文件中的第36行是定义方法的行:

public void testRunLocalhost() throws IOException, InterruptedException {

我不明白违规行为是什么。我应该在哪里定义这三个变量?为什么不是违规的播音员?它的声明方式与我尝试重新排序声明无效。

2 个答案:

答案 0 :(得分:3)

在分配这三个最终变量之后,它似乎与您正在进行的assert调用有关。

PMD文档(http://pmd.sourceforge.net/rules/controversial.html#DataflowAnomalyAnalysis)说:

  

UR - 异常:有一个未在

之前定义的变量的引用

答案 1 :(得分:0)

这看起来很奇怪。有趣的是,它发生在为通过'new'分配的对象定义的所有三个变量中,然后检查是否为null。我希望'new'的结果总是有效/不为null - 否则应抛出OutOfMemoryException。这是问题,我想知道吗?