📄 tutorial.pod
字号:
demo.minMaxDemo(); } }=head2 2.3.4 Passing Arrays of ObjectsWorking with arrays of objects is a little more complicated, because youneed to work with them one at a time.Fetch one element at a time with GetObjectArrayElement(), which returnsan object of type java.lang.Object (the most generic type). Explicitly cast the Object to its real type with bless(). perl void sortArray( String[] names ) {{ my @new_array; for (my $i = 0; $i < GetArrayLength($names); $i++) { my $string = GetObjectArrayElement($names, $i); bless $string, "java::lang::String"; push @new_array, $string; } print join(', ', sort @new_array), "\n"; }} void arrayDemo() { String[] names = {"Omega", "Gamma", "Beta", "Alpha"}; sortArray( names ); }Note. String is not a primitive type: it is a class (java.lang.String).So, you need to use this technique for Strings as well. You can't usethe technique in 2.3.3.PerlTakesObjectArray.jpl public class PerlTakesObjectArray { // Perl method to sort an array of strings. // perl void sortArray( String[] names ) {{ my @new_array; # an array to copy names[] to # Fetch each element from the array. for (my $i = 0; $i < GetArrayLength($names); $i++) { # Get the object (it's not a String yet!) at # the current index ($i). my $string = GetObjectArrayElement($names, $i); # Cast (bless) it into a String. bless $string, "java::lang::String"; # Add it to the array. push @new_array, $string; } # Print the sorted, comma-delimited array. print join(', ', sort @new_array), "\n"; }} // Create a String array and ask Perl to sort it for us. // void arrayDemo() { String[] names = {"Omega", "Gamma", "Beta", "Alpha"}; sortArray( names ); } public static void main(String[] argv) { PerlTakesObjectArray demo = new PerlTakesObjectArray(); demo.arrayDemo(); } }=head2 2.3.5 Returning Arrays from Perl to JavaTo write a Perl method that returns an array, declare its return valueas an array type. Make sure you return a reference to the array, not alist: perl int[] getTime() {{ my ($sec, $min, $hour, @unused) = localtime(time); # Return an array with seconds, minutes, hours my @time_array = ($sec, $min, $hour); return \@time_array; }} void testArray() { int time[] = getTime(); System.out.println(time[2] + ":" + time[1]); }PerlGivesArray.jpl // Simple JPL demo to show how to send an array to Java // from Perl class PerlGivesArray { // Call the Perl method to get an array and print // the hour and minute elements. void testArray() { int time[] = getTime(); System.out.println(time[2] + ":" + time[1]); } // Perl method that returns an array reference. // perl int[] getTime() {{ # Get the first three arguments from localtime, # discard the rest. my ($sec, $min, $hour, @unused) = localtime(time); # Return an array with seconds, minutes, hours my @time_array = ($sec, $min, $hour); return \@time_array; }} public static void main(String[] argv) { PerlGivesArray demo = new PerlGivesArray(); demo.testArray(); } }=head2 2.3.6 Arrays from StringsJPL will slice Perl strings up into Java arrays for you. If you declarea Perl method as an array type and return a string (instead of an arrayreference), JPL splits up the elements into an array.Consider this example, where a GIF stored in a string gets turned intoan array of bytes so Java can make an Image out of it: void generateImage() { Toolkit kit = Toolkit.getDefaultToolkit(); byte[] image_data = mkImage(); img = kit.createImage( image_data ); } perl byte[] mkImage() {{ use GD; my $im = new GD::Image( $self->width, $self->height); my $white = $im->colorAllocate(255, 255, 255); my $blue = $im->colorAllocate(0, 0, 255); $im->fill($white, 0, 0); $im->string(gdLargeFont, 10, 10, "Hello, World", $blue); return $im->gif; }}GifDemo.jpl import java.awt.*; import java.awt.event.*; import java.awt.image.*; /* * A JPL program that demonstrates passing byte arrays * between Java and Perl * */ class GIFDemo extends Canvas { Image img; int width = 200; int height = 30; // Constructor for this class. public GIFDemo() { this.setSize(width, height); } // Java method to create an image. // void generateImage() { Toolkit kit = Toolkit.getDefaultToolkit(); // Invoke the mkImage() Perl method to generate an // image. byte[] image_data = mkImage(); // Create the image with the byte array we got // from the Perl method. img = kit.createImage( image_data ); } // A Perl method to generate an image. perl byte[] mkImage() {{ # Use the GD image manipulation extension. use GD; # Create a new image with the height and width specified # in the enclosing Java class. my $im = new GD::Image( $self->width, $self->height); # Allocate two colors. my $white = $im->colorAllocate(255, 255, 255); my $blue = $im->colorAllocate(0, 0, 255); # Fill the image with white and draw a greeting. $im->fill($white, 0, 0); $im->string(gdLargeFont, 10, 10, "Hello, World", $blue); return $im->gif; }} // Java uses this to repaint the image when necessary. public void paint(Graphics g) { g.drawImage(img, 0, 0, this); } // The entry point. public static void main(String[] argv) { // Set up a frame and create an image. Frame f = new Frame("GD Example"); f.setLayout(new BorderLayout()); GIFDemo demo = new GIFDemo(); demo.generateImage(); f.add("Center", demo); f.addWindowListener( new Handler() ); f.pack(); f.show(); } } // A handler to process a request to close a window. class Handler extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } }=head2 2.3.7 Summary: Calling Perl from Java=over 4=item 1 Put your embedded Perl code in methods that are declared C<perl>. =item 2 Use double, rather than single, curly braces ({{ and }}). =item 3 Invoke the Perl methods from Java just like any other Java method. =item 4 No need to pull arguments off of C<@_> with C<shift>: JPL takes care ofthis for you. This includes C<$self>. =item 5 If you pass a Java array into a Perl method, it comes in as a scalarreference. =item 6 Convert references to arrays of primitives with C<Get*ArrayElements> =item 7 Use C<GetObjectArrayElement> to get elements from arrays of strings andother objects. =item 8 To return an array from a C<perl> method, declare the method as returningan array type, and either: =item 9 Return an array reference. =item 10 Return a string: JPL slices it up for you.=back=head1 2.4 Calling Java from PerlNext, let's look at how to invoke Java from Perl. =head2 2.4.1 Java in Perl in JavaRemember the issues from 2.1.2 - this is unstable unless you are calling Java from Perl methods that are themselves embedded in a Java program.=head2 2.4.2 Java in Perl: Simple ConstructorsUse JPL::Class to load the class:C<use JPL::Class "java::awt::Frame";>Invoke the constructor to create an instance of the class:C<my $f = java::awt::Frame->new;>You've got a reference to a Java object in $f, a Perl scalar. I thinkthis is cool.=head2 2.4.3 Constructors that Take ParametersIf the constructor has parameters, look up the method signature withC<getmeth>:my $new = getmeth("new", ['java.lang.String'], []);The first argument to C<getmeth> is the name of the method. The secondargument is a reference to an array that contains a list of the argumenttypes. The final argument to C<getmeth> is a reference to an arraycontaining a single element with the return type. Constructors alwayshave a null (void) return type, even though they return an instance ofan object.Invoke the method through the variable you created:my $f = java::awt::Frame->$new( "Frame Demo" );Because Java supports method overloading, the only way Java candistinguish between different methods that have the same name is throughthe method signature. The C<getmeth> function simply returns a mangled,Perl-friendly version of the signature. JPL's AutoLoader takes care offinding the right class.For example, the method signature for $new is C<(Ljava/lang/String;)V>.In Perl, this is translated to C<new__Ljava_lang_String_2__V>. Sure, itmeans something to Java, but thanks to C<getmeth> and JPL's AutoLoader,we don't have to worry about it!=head2 2.4.4 More on getmethThe C<getmeth> function is not just for constructors. You'll use it to lookup method signatures for any method that takes arguments.To use C<getmeth>, just supply the Java names of the types and objects inthe argument or return value list. Here are a few examples:=over 4=item *Two int arguments, void return type: $setSize = getmeth("setSize", ['int', 'int'], []);=item *One argument (java.awt.Component), with a return type of the same: $add = getmeth("add", ['java.awt.Component'], ['java.awt.Component']);=item *Two arguments, a String object and a boolean value, and a void returntype: $new = getmeth("new", ['java.lang.String', 'boolean'], []);=item *A String argument with a java.lang.Class return type: $forName = getmeth("forName", ['java.lang.String'], ['java.lang.Class']);=item *No arguments, but a boolean return value: $next = getmeth("next", [], ['boolean']);=back=head2 2.4.5 Instance VariablesJava instance variables that belong to a class can be reached through$self and a method with the same name as the instance variables: $frame->$setSize( $self->width, $self->height );Here is an example: class VarDemo { int foo = 100; perl int perlChange() {{ my $current_value = $self->foo; # Change foo to ten times itself. $self->foo( $current_value * 10 ); }} void executeChange() { perlChange(); System.out.println(foo); } public static void main(String[] args) { VarDemo demo = new VarDemo(); demo.executeChange(); } }Note. JPL creates these methods with the same name as the variable. Youcan also supply a value to set the variable's value. If you create amethod with this name, it will collide with the one that JPL defines.FrameDemo.jpl /* * FrameDemo - create and show a Frame in Perl. * */ public class FrameDemo { int height = 50; int width = 200; perl void make_frame () {{ # Import two Java classes. use JPL::Class "java::awt::Frame"; use JPL::Class "java::awt::Button"; # Create a Frame and a Button. The two calls to new() # have the same signature. my $new = getmeth("new", ['java.lang.String'], []); my $frame = java::awt::Frame->$new( "Frame Demo" ); my $btn = java::awt::Button->$new( "Do Not Press Me" ); # Add the button to the frame. my $add = getmeth("add", ['java.awt.Component'], ['java.awt.Component']); $frame->$add( $btn ); # Set the size of the frame and show it. my $setSize = getmeth("setSize", ['int', 'int'], []); $frame->$setSize($self->width, $self->height); $frame->show; }} public static void main(String[] argv) { FrameDemo demo = new FrameDemo(); demo.make_frame(); } }=head2 2.4.6 Summary: Calling Java from Perl=over 4=item 1 Use JPL::Class to specify a Java class to import. =item 2 You can directly invoke constructors and methods that take no arguments. =item 3 If the constructor or method takes arguments, use getmeth to look up itssignature. =item 4 Use $self to access Java instance variables and methods.=back=head1 COPYRIGHTCopyright (c) 1999, Brian JepsonYou may distribute this file under the same terms as Perl itself.Converted from FrameMaker by Kevin Falcone.=cut
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -