我尝试使用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);
}
}发布于 2019-05-29 07:20:51
这是因为,类没有加载到类路径中。编译并将类加载到类路径解决了这个问题。
https://stackoverflow.com/questions/56285235
复制相似问题