Web3J自动生成Java包装器

时间:2019-05-24 02:49:44

标签: java-8 solidity web3

我试图使用web3j动态生成包装器,并使用反射在生成的类上调用方法。但是我第一次尝试时遇到classNotFound异常。 (当我停止服务器并重新运行时,它可以工作,因为该类已经存在)

java是否支持动态生成类(服务器运行时)?

 private void createContractClass(String contractFileNameWithoutExtension) {
        try {
            String command = "web3j solidity generate -b " +
                    contractLocation+contractFileNameWithoutExtension+".bin  -a "+contractLocation+contractFileNameWithoutExtension+".abi" +
                    " -o "+sourceCodeLocation+" -p generated";
            LOG.info("Executing {}", command);
            Process p = Runtime.getRuntime().exec(command);
            int exitCode = p.waitFor();
            if(exitCode != 0) {
                LOG.error("Error {}", p.getOutputStream());
            }
        } catch(IOException | InterruptedException ex) {
            ex.printStackTrace();
            throw new FormatException(ValidationMessages.FAILED_TO_DEPLOY_CONTRACT);
        }
    }

 private String invokeDeployment(String password, String walletFileName, String contractFileName) {
        try {
            Credentials credentials = WalletUtils.loadCredentials(password, walletLocation + "/" + walletFileName);
            Class classz = Class.forName("generated."+ StringUtils.capitalize(contractFileName));
            Method method = classz.getDeclaredMethod("deploy", Web3j.class, Credentials.class, BigInteger.class, BigInteger.class);

            RemoteCall<?> invoke = (RemoteCall<?>)method.invoke(classz, web3JClient.getClient(), credentials, DefaultGasProvider.GAS_PRICE, DefaultGasProvider.GAS_LIMIT);
            Contract contract = (Contract)invoke.send();
            return contract.getContractAddress();
        } catch (Exception e){
            e.printStackTrace();
            throw new FormatException(ValidationMessages.FAILED_TO_DEPLOY_CONTRACT);
        }
    }

1 个答案:

答案 0 :(得分:0)

这是因为未将类加载到类路径中。编译并将类加载到类路径即可解决该问题。