Is there a workaround to conditionally import java class to import list in MATLAB?

13 views (last 30 days)
I guess the answer is no, but I'd like to try.
Is there a workaround to conditionally import java class to import list in MATLAB? The documentation of MATLAB simply denies it.
> Do not use import in conditional statements inside a function. MATLAB preprocesses the import statement before evaluating the variables in the conditional statements.
function func1()
...
if A
import ij.process.LUT
end
...
end
I wanted to implement something like this in a function, because it is not guaranteed that ij.process.LUT is within MATLAB's scope. Simply calling import ij.process.LUT will cause an error in some scenarios.
The following trick did not work, since it appears that MATLAB evaluates import statements before actually running code.
function func2()
...
try
if A
import ij.process.LUT
end
catch
end
...
end

Accepted Answer

Kouichi C. Nakamura
Kouichi C. Nakamura on 5 Apr 2018
Edited: Kouichi C. Nakamura on 5 Apr 2018
Actually, I might have found a workaround.
function testfun1()
if 0
import ij.process.LUT
end
disp('OK')
end
In this example, the import statement is never reachable, but if you run testfun1, you'll get an error.
>> testfun1
Error: File: testfun1.m Line: 5 Column: 12
Arguments to IMPORT must either end with ".*" or else specify a fully qualified class name:
"ij.process.LUT" fails this test.
This is because "MATLAB preprocesses the import statement before evaluating the variables in the conditional statements" and because ij.process.LUT is not in MATLAB's scope now (you can assess by|javaclasspath|).
This happens even in a local function in a function M file.
function testfun1b()
if 0
localfun();
end
disp('OK')
end
%------------------------------
function localfun()
import ij.process.LUT
end
Although import statement in localfun is unreachable, you'll get the same error.
>> testfun1b
Error: File: testfun1b.m Line: 16 Column: 8
Arguments to IMPORT must either end with ".*" or else specify a fully qualified class name:
"ij.process.LUT" fails this test.
However, if you put import statement in a separate function M file, like this one below,
function testfun2()
import ij.process.LUT
end
then, the testfun1 can be rewritten as below:
function testfun3()
if 0
testfun2();
end
disp('OK')
end
Again, when you execute testfun3, the import statement is unreachable again due to if statement, and it does not issue an error.
>> testfun3
OK
Short answer:
Put import statement(s) in a separate function M file and call that function conditionally.

More Answers (1)

Kouichi C. Nakamura
Kouichi C. Nakamura on 17 May 2018
This really is a cheating, but calling `func1` does not issue an error. Putting `import` statement into `eval` is one way. There might be potential drawbacks.
function func1()
if 0
eval('import ij.process.LUT')
end
end

Community Treasure Hunt

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

Start Hunting!