我正在尝试使用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);
}
}
是因为,该类未加载在类路径中。编译并将类加载到类路径上解决了问题。