0

这是我在私人网络中的简单合同

contract AB {
    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function AB () {
        balanceOf[msg.sender] = 1200;              // Give the creator all initial tokens
    }

    /* Send coins */
    function transfer(address _to, uint256 _value) {
        if (balanceOf[msg.sender] < _value) throw;           // Check if the sender has enough
        if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
        balanceOf[msg.sender] -= _value;                     // Subtract from the sender
        balanceOf[_to] += _value;                            // Add the same to the recipient
    }

    function gettokenBalance(address to)constant returns (uint256){
          return balanceOf[to];
       }
}

我已经使用 web3J 生成了智能合约包装器,并且有类似的功能

public Future<Uint256> gettokenBalance(Address to) {
        Function function = new Function("gettokenBalance", 
                Arrays.<Type>asList(to), 
                Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));
        return executeCallSingleValueReturnAsync(function);
    }

当我试图访问我的合同功能时

AB newAB = AB.load(contractaddress, web3j, credentials, gasprice, gaslimit);
        Future<Uint256> result = newAB.gettokenBalance(new Address(address));
        LOGGER.info("result:::"+result.get());

它给了我一个例外

 java.util.concurrent.ExecutionException: java.lang.IndexOutOfBoundsException: Index: 0
    at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357) ~[na:1.8.0_91]
    at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895) ~[na:1.8.0_91]
    at com.belrium.service.UserWalletService.check(UserWalletService.java:197) ~[classes/:na]
    at com.belrium.controller.UserController.check(UserController.java:119) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]

请帮忙。

4

1 回答 1

0

Futures 是异步的,因此get()会尝试获取当前仍在计算的结果值。它仅在计算完成后才起作用。

我认为 Java Future API 不支持你想要的。相反,我可以推荐使用CompletableFuture,它有一种join()方法可以完全满足您的要求:等待并获取。

当我从合约生成代码时,我遇到了同样的问题。所以我放弃了生成器,并用 s 替换了Future我生成的代码中的所有CompletableFutures。我认为这是 web3j 的疏忽,尽管可能有一种我不知道的不同方法来处理这个问题!

于 2017-07-05T13:58:35.050 回答