Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java and Mathematica interaction

How can I use Java within Mathematica?

I have two files,GRASP.nb and GRASP.java, in the same folder (BTW: GRASP=greedy randomized adaptive search procedure). The GRASP.java file contains a method public static int[] TSP(int[][] g, int numberOfIterations, int k). I'd like to call this method within Mathematica.

I read in the Mathematica documentation, and also here, that I should write

Needs["JLink`"]; 
InstallJava[]; 
obj=JavaNew[NotebookDirectory[]~~"GRASP.java"]

or

Needs["JLink`"]; 
InstallJava[]; 
obj=LoadJavaClass[NotebookDirectory[]~~"GRASP.java"]

or something like it, but anything I try, returns an error. I have WinXP, Mathematica 7, Eclipse 3.6.

Any working example would be much appreciated.

like image 730
Leo Avatar asked Feb 25 '23 06:02

Leo


1 Answers

Don't forget to compile the Java class first -- you cannot load GRASP.java directly.

After compilation, try the following:

Needs["JLink`"]
AddToClassPath[NotebookDirectory[]];
LoadJavaClass["GRASP"];
GRASP`TSP[{{1,2,3},{4,5,6}}, 7, 8]

Since the TSP method is a static method, you must load the Java class itself before you can access it. Note that the class becomes a Mathematica context named GRASP and that the static method is accessed as a symbol in that context (GRASP`TSP, as shown above).

If the method you wanted to access were a regular method (not static), then the calling sequence would look like this instead:

Needs["JLink`"]
AddToClassPath[NotebookDirectory[]];
obj = JavaNew["GRASP"];
obj@someMethod[{{1,2,3},{4,5,6}}, 7, 8]

All of this assumes that your Java class is contained in the default package -- an unusual circumstance. If the class were contained in a named package, then the syntax would be like this:

Needs["JLink`"]
AddToClassPath[NotebookDirectory[]];
LoadJavaClass["com.stackoverflow.GRASP"];
com`stackoverflow`GRASP`TSP[{{1,2,3},{4,5,6}}, 7, 8]

or

Needs["JLink`"]
AddToClassPath[NotebookDirectory[]];
obj = JavaNew["com.stackoverflow.GRASP"];
obj@someMethod[{{1,2,3},{4,5,6}}, 7, 8]

If the class is in a named package (com.stackoverflow in my examples), then make sure that the class has the path com/stackoverflow/GRASP.class relative to the notebook. This is a requirement of Java, not Mathematica.

like image 86
WReach Avatar answered Feb 26 '23 21:02

WReach