Reputation: 1
We got a requirement to call a static method inside a Java class via perl script and capture the return value of the method as we have to remove the syso statements in the Java code.
Sample Java class
public class SampleClass
{
public static void main (String [] args) throws Exception
{
var_1 = func(arg1,arg2);
System.out.print(var_1);
}
private static String func(final String arg1, final String arg2)
throws Exception
{
<--- code -->
return value;
}
public static String SampleMethod(final String arg1, final String arg2)
throws Exception
{
var_2 = func(arg1,arg2);
return var_2;
}
}
Intially in perl we are calling the actual class like below
command = SampleClass Arg_1 Arg 2
`$command`
Now the requirement is to call the SampleMethod
and capture the return value to avoid reading the o/p from console.
Tried the below
command = SampleClass.SampleMethod Arg_1 Arg 2
`$command`
But it failed saying unable to load main class in SampleMethod
Please advise.
Upvotes: 0
Views: 253
Reputation: 40778
You cannot call other static methods than main()
in a Java class from Perl. A workaround is to wrap the static method inside another class with a static main() that calls the original static method, see also this answer. For example:
SampleClass.java:
public class SampleClass
{
public static void main(String [] args) throws Exception
{
String result = SampleMethod("string1", "string2");
System.out.println("Result: " + result);
}
public static String SampleMethod(final String arg1, final String arg2)
throws Exception
{
return arg1 + " " + arg2;
}
}
p.pl:
use feature qw(say);
use strict;
use warnings;
my $wrap_name = 'Wrapper';
my $source = <<"END_JAVA";
class $wrap_name {
public static void main(String[] args) throws Exception {
String result = SampleClass.SampleMethod("string1", "string2");
System.out.print("Result: " + result);
}
}
END_JAVA
my $fn = $wrap_name . '.java';
open ( my $fh, '>', $fn ) or die "Could not open file '$fn': $!";
print $fh $source;
close $fh;
system 'javac', $fn;
my $output = `java ${wrap_name}`;
say "Got output: '$output'";
You can then run:
$ javac SampleClass.java
$ perl p.pl
Got output: 'Result: string1 string2'
Upvotes: 2