The JVM ecosystem provides robust tools for Ethereum development, primarily through the Web3j library which works with both Java and Kotlin.
Comprehensive Java and Kotlin library for Ethereum.
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Convert;
import java.math.BigDecimal;
public class EthereumClient {
private final Web3j web3j;
public EthereumClient(String nodeUrl) {
this.web3j = Web3j.build(new HttpService(nodeUrl));
}
public BigDecimal getBalance(String address) throws Exception {
BigInteger balanceWei = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST)
.send()
.getBalance();
return Convert.fromWei(balanceWei.toString(), Convert.Unit.ETHER);
}
public String sendTransaction(Credentials credentials, String toAddress, BigDecimal ethAmount) {
BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
BigInteger value = Convert.toWei(ethAmount, Convert.Unit.ETHER).toBigInteger();
RawTransaction rawTransaction = RawTransaction.createEtherTransaction(
nonce, gasPrice, GAS_LIMIT, toAddress, value);
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);
return web3j.ethSendRawTransaction(hexValue).send().getTransactionHash();
}
}
import org.web3j.protocol.Web3j
import org.web3j.protocol.http.HttpService
import org.web3j.utils.Convert
import java.math.BigDecimal
class EthereumClient(nodeUrl: String) {
private val web3j = Web3j.build(HttpService(nodeUrl))
suspend fun getBalance(address: String): BigDecimal {
val balanceWei = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST)
.send()
.balance
return Convert.fromWei(balanceWei.toString(), Convert.Unit.ETHER)
}
suspend fun sendTransaction(
credentials: Credentials,
toAddress: String,
ethAmount: BigDecimal
): String {
val gasPrice = web3j.ethGasPrice().send().gasPrice
val value = Convert.toWei(ethAmount, Convert.Unit.ETHER).toBigInteger()
val rawTransaction = RawTransaction.createEtherTransaction(
nonce, gasPrice, GAS_LIMIT, toAddress, value)
val signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials)
val hexValue = Numeric.toHexString(signedMessage)
return web3j.ethSendRawTransaction(hexValue).send().transactionHash
}
}
Web3j provides specific features for Android development:
// Android example
class EthereumViewModel : ViewModel() {
private val web3j = Web3j.build(HttpService("YOUR_ETHEREUM_NODE_URL"))
fun getBalance(address: String) = viewModelScope.launch {
withContext(Dispatchers.IO) {
val balance = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST)
.send()
.balance
// Update UI
}
}
}
Generate contract wrappers from Solidity:
web3j solidity generate /path/to/contract.sol -o /path/to/output -p com.your.package
Then use in your code:
val contract = YourContract.load(
contractAddress,
web3j,
credentials,
gasPrice,
gasLimit
)
// Call contract method
val result = contract.someMethod().send()