Modifying the dynamic Java classpath when Java objects are loaded

5 views (last 30 days)
I have a problem updating MATLAB's dynamic Java classpath when there are variables in the workspace that point to Java objects whose classes are on the dynamic classpath.
I have two Java test classes matlabtest.Test1 and matlabtest.Test2:
>> ls java1\matlabtest\
. .. Test1.class
>> ls java2\matlabtest\
. .. Test2.class
Adding the first directory to the classpath and instantiating matlabtest.Test1 is not a problem:
>> javaaddpath('java1')
>> test1 = matlabtest.Test1()
test1 =
matlabtest.Test1@606032
However, now adding the second directory and instantiating matlabtest.Test2 does not work:
>> javaaddpath('java2')
Warning: Objects of matlabtest/Test1 class exist - not clearing java
> In javaclasspath>doclear at 379
In javaclasspath>local_javapath at 197
In javaclasspath at 119
In javaaddpath at 69
>> test2 = matlabtest.Test2()
??? Undefined variable "matlabtest" or class "matlabtest.Test2".
A workaround:
>> clear test1;
>> clear java;
>> test2 = matlabtest.Test2()
test2 =
matlabtest.Test2@fcc070
However, this workaround is not possible in my case (the relevant objects belong to another product and I cannot simply clear them without upsetting my users). I also cannot MATLAB's static Java classpath (the exact directories are only known at runtime).
So: How can I create Java objects from truly dynamic locations?

Answers (1)

Jacob Halbrooks
Jacob Halbrooks on 16 Mar 2012
Steve Lord answered a similar question on the MATLAB Newsgroup. I think his answer also applies to your question. Here is what he wrote:
When you call JAVAADDPATH, it calls CLEAR with the flag 'java' as part of its execution.
As documented on the reference page for CLEAR, "clear java" behaves like "clear all" in that it clears all variables from the base workspace.
If you want to recover those variables you need to either SAVE them before calling JAVAADDPATH and LOAD them afterwards or reexecute the code that generated those variables.
  2 Comments
Florian Brucker
Florian Brucker on 16 Mar 2012
My problem is not that |clear java| performs a |clear all|. My problem is that |clear java| is not performed at all since there are variables in the workspace which point to instances of Java objects and that it is impossible to modify the dynamic classpath without calling |clear java| (explicitely or implicitely via |javaaddpath|).
Jacob Halbrooks
Jacob Halbrooks on 16 Mar 2012
I think that is all correct; you ultimately need to clear your existing Java variables to add a new Java path. As a result, you need to follow one of the work-arounds suggested by Steve to recover those variables.

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!