Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Using Java methods in perl

by AcidHawk (Vicar)
on Sep 20, 2004 at 18:27 UTC ( [id://392445]=perlquestion: print w/replies, xml ) Need Help??

AcidHawk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I have a Java class, which contains methods that I would realy like to use from a perl script. Typically I would like to do something like

use java::myJavaApp.class; $obj = new myJavaApp(); #Create a new object ..? $result = $obj->myMethod1($arg1, $arg2, $arg3); #Result conains the re +turn from the Java method.

Has any-one used any of the java modules on CPAN?
Which module have you had most success with (with the least amount of blood lost)?

Cheers
AcidHawk

-----
Of all the things I've lost in my life, its my mind I miss the most.

Replies are listed 'Best First'.
Re: Using Java methods in perl
by hardburn (Abbot) on Sep 20, 2004 at 18:35 UTC

    I've never used it myself, but I believe Inline::Java is what you're looking for.

    "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

      Inline::Java allows you to put Java source code directly "inline" in a Perl script or module.

      I have a class file not the source. I could just go a re-write the source but that would take far too long and really defeat my objective, which is to use stuff that I have already got.

      Thanks for the thought though.

      -----
      Of all the things I've lost in my life, its my mind I miss the most.
        I have a class file not the source.

        No problem, Inline::Java handles that too. Just use the STUDY and AUTOSTUDY options. I'm using Inline::Java to access a 3rd-party vendor's API right now and it's working great.

        -sam

        The following code illustrates STUDYing a class with Inline::Java. Other classes encountered when the code is first run are examined courtesy of the AUTOSTUDY statement. The class info is cached so that future execution is quicker.

        #! /usr/bin/perl -w use strict; use warnings; use Data::Dumper; use Inline ( Java => 'STUDY', STUDY => ['com.verity.search.VSearch'], AUTOSTUDY => 1, ); use Inline::Java qw(caught) ; eval { my $search = new com::verity::search::VSearch(); $search->setServerSpec('localhost:9900'); $search->setK2UserName('inman'); $search->setK2Password('xxxxx'); my $ticket = $search->k2Login();; my $colls = $search->collectionsInfo(); my $collCount = $colls->count(); foreach (0..$collCount-1) { my $coll = $colls->at($_); print "Collection: ".$coll->getAlias."\n"; } $search->addCollection ('verity_doccoll'); $search->setQueryText('*'); my $result = $search->getResult(); print "Docs Found: ", $result->{docsFound}; }; if ($@) { if (caught("java.lang.Exception")) { my $msg; $msg = ($@->getMessage()); print "Exception $msg\n"; # prints ouch! } else { # It wasn't a Java exception after all... die $@ ; } }

        Instead of copy-and-pasting the source of the orginal class, you could make a simple class that imports the orginal class and dispatches its methods back there.

        "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

Re: Using Java methods in perl
by jryan (Vicar) on Sep 20, 2004 at 21:24 UTC

    I was sitting in the middle of a boring presentation, and I saw this post and thought "Hey, I'm pretty bored at the moment, I'll write an auto-dispatcher for him!". Of course, by the I finished it, samtregar had already responded with the correct solution. :)

    But, I'm going to post my solution anyways (even though it definitely isn't the optimal solution here), just because you might find it interesting. Also note that I do not have java/perl access on the lab computers that we are using, so this code is most definitely untested.

    package Inline::Java::Classfile; sub new { my ($type, $args) = @_; Inline->bind(Java => << "__CODE__"); // package org.perl.cpan.inline.java; import java.lang.*; import java.lang.reflect.*; class InlineJavaDispatcher { protected $type inst; public InlineJavaDispatcher(Object[] args) throws InstantiationException ,IllegalAccessException ,IllegalArgumentException ,InvocationTargetException ,SecurityException { Class clazz = $type.class; Constructor[] cntrs = clazz.getDeclaredConstructors(); for (int i=0; i < cntrs.length(); i++) { try { inst = cntrs[i].newInstance(args); return; } catch (IllegalArgumentException e) { } } throw new IllegalArgumentException( methodName + " was not found for the arguments supplied fo +r Class $type." ); } public Object dispatch(String methodName ,Object[] args) throws IllegalAccessException ,IllegalArgumentException ,InvocationTargetException ,NullPointerException ,ExceptionInInitializerError { Class clazz = inst.getClass(); Method am[] = inst.getDeclaredMethods(); for (int i=0; i < am.length; i++) { if (am[i].getName().equals(methodName)) { try { return am[i].invoke(inst, args); } catch (IllegalArgumentException e) { } } } throw new IllegalArgumentException( methodName + " was not found for the arguments supplied fo +r Class $type." ); } } __CODE__ return InlineJavaDispatcher->new($args); } sub AUTOLOAD { my ($self,$args) = shift; my $type = ref($self) or croak "$self is not an object"; my $name = $AUTOLOAD; $name =~ s/.*://; # strip fully-qualified portion $self->dispatch($name, $args); }

    Usage would be:

    my $obj = Inline::Java::Classfile->new("SomeClass", [$cntr_arg1, $ +arg2, $etc]); print $obj->hashcode(); # or whatever method

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://392445]
Approved by ikegami
Front-paged by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (4)
As of 2024-04-25 15:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found