You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Web3j调用ethGetBlockByNumber报错:无法对非静态方法做静态引用

问题解决及优化方案

错误原因

你遇到的Cannot make a static reference to the non-static method错误,是因为ethGetBlockByNumber是Web3j的实例方法,不能直接通过Web3j类名静态调用,必须先创建Web3j的实例,建立与以太坊节点的连接后才能调用。

修正后的代码示例

下面是修复错误并适配你需求(获取交易回执)的完整代码:

import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.EthTransactionReceipt;
import org.web3j.protocol.http.HttpService;
import java.util.List;

public class BlockProcessor {

    public void GetLatestBlock() throws Exception {
        // 1. 初始化Web3j实例,连接到以太坊节点(示例用本地节点,可替换为Infura等远程节点URL)
        Web3j web3j = Web3j.build(new HttpService("http://localhost:8545"));

        // 2. 通过实例调用方法,获取最新区块的交易列表
        EthBlock block = web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, true).send().getBlock();
        List<EthBlock.TransactionResult> txs = block.getTransactions();

        // 3. 遍历交易,逐个获取交易回执
        for (EthBlock.TransactionResult txResult : txs) {
            EthBlock.TransactionObject transaction = (EthBlock.TransactionObject) txResult.get();
            String txHash = transaction.getHash();

            // 查询并处理交易回执
            EthTransactionReceipt receiptResponse = web3j.ethGetTransactionReceipt(txHash).send();
            receiptResponse.getTransactionReceipt().ifPresent(receipt -> {
                System.out.println("交易哈希: " + txHash);
                System.out.println("所属区块哈希: " + receipt.getBlockHash());
                System.out.println("实际消耗燃气: " + receipt.getGasUsed());
            });
        }

        // 4. 关闭连接,避免资源泄漏
        web3j.shutdown();
    }
}

关于计算哈希率的思路

哈希率(Hashrate)的计算分两种场景:

  • 网络整体哈希率:用区块难度和出块时间计算,公式为哈希率 = 区块难度 * 2^32 / 出块间隔(秒)。你可以通过block.getDifficulty()获取当前区块难度,结合前后区块的时间戳算出出块间隔。
  • 单个矿工算力:统计该矿工在一段时间内挖出的所有区块,累加这些区块的难度值,再除以时间跨度,得到该矿工的平均算力。

内容的提问来源于stack exchange,提问作者李林發

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:20:28