Leo
Leo

Reputation: 781

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.

Upvotes: 4

Views: 1298

Answers (2)

WReach
WReach

Reputation: 18271

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.

Upvotes: 7

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

The StackOverflow post you link to shows the name of the Java class (GRASP) not the name of the source file, being passed as the argument, so definitely lose the .java. Also, you'll need to compile the source file to produce a GRASP.class file, as that's the format that can actually be loaded. That might be as simple as just

javac GRASP.java

but it might be harder, depending on what's in that file. Likewise, the name of the class might not be just GRASP -- if there's a package com.foo.something statement in the file, then the argument is going to be com.foo.something.GRASP.

Upvotes: 1

Related Questions