Simple Example: Calling Java From Clojure

For most people who have programmed in Java, the following is “Ok, so what’s the big deal?” moment. I maintained a Java application years ago, but have not dealt much with Java builds, paths, or  packages.

The following is an example of needing to create a Java class to hold data for a Clojure program.

Here is the project file:

(defproject ba2-app "0.0.1-SNAPSHOT"
:description "TODO: add summary of your project"
:source-path "src"
:java-source-path "src"
:dependencies [[org.clojure/clojure "1.2.1"]
[org.clojure/tools.cli "0.1.0"]]
:main ba2-app)

Header from ba2_app.clj:

(ns ba2-app
(:import Account)
(:use [clojure.string :only [split]]
[clojure.string :only [join]]))

Java class:

import java.util.Date;

public class Account {

public Account( int in_acct_num,
char in_acct_type)
acct_num = in_acct_num;
acct_type = in_acct_type;

public int getAcctNum () {return acct_num;}

public char getAcctType () {return acct_type;}

public double getTransAmt() {return trans_amt;}
public void   setTransAmt(double in_trans_amt) {trans_amt = in_trans_amt;}

public double getCurBal() {return cur_bal;}
public void setCurBal(double in_cur_bal) {cur_bal = in_cur_bal;}

public Date getLastUpdate() {return last_update;}
public void setLastUpdate(Date in_last_update) {last_update = in_last_update;}

private int acct_num;
private char acct_type;
private double trans_amt;
private double cur_bal;
private Date last_update;

Create instance and test:

ba2-app=> (def test-acct (Account. 1000 M))
#’ba2-app/test-acctba2-app=> (.getAcctNum test-acct)

Oh, and as a side note, I’ve switched to leiningen, which immediately built my Java ( class without a fuss.



Filed under Clojure, Java

2 responses to “Simple Example: Calling Java From Clojure

  1. andrew

    Hi…would be nice see see other examples about java-clojure iteraction…In the web I only found very basic examples..thanks

    • Octopusgrabbus

      I’ll post the final of this assignment when I’m done with it. This is one case — I’ve got to find the link, where there explanation was quite helpful in how to invoke a method.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s