Kevin White writes:
> I am having a tough time piecing together the (lack of) documentation on
> using native code to actually allocate (and call the constructor of) a
> new object.  Can someone please point me to an example?  I have a java
> class that needs to be constructed by some native code.  It will take 4
> parameters in the constructor, so I'd like to see a sample with multiple
> paramters.

You "just" use the standard ways to call Java methods from JNI code. :-)

Call Class.forName(String) to get an Object that corresponds to the
class you want to allocate.  Then call getDeclaredConstructors() on
that object; that will return an array of objects having type
Constructor.  Search through that array until you find the Constructor
of four arguments that you want.  Finally, call newInstance() on that
Constructor object, passing it array of type Object that contains each
of the arguments you want to pass.

That's really complicated, so there are a few ways to cheat.  Let
NativeClass be the class containing your native method, let
TargetClass be the class you want your native method to instantiate,
and assume that you want to run the following constructor:
        public TargetClass (int n, double d, String s, Vector v) { ... }

Then you can use a static initializer to find the constructor you want
and assign it to a static member variable.

        package com.foobar;

        public class NativeClass {
            static Constructor cons;
            static {
                final Class cTarget = Class.forName ("com.foobar.TargetClass");
                final Class cStr = Class.forName ("java.lang.String");
                final Class cVec = Class.forName ("java.lang.Vector");
                cons = c.getConstructor
                    (new Class [] { Integer.TYPE, Double.TYPE, cStr, cVec });
            }
            // ...
            // various native method declarations here
        }

Now all your JNI code has to do is get the static field named "cons",
create an Object [] containing the arguments to the constructor, and
call the newInstance(Object []) method.

Best,
daniel dulitz

Valley Technologis, Inc.                Peak Performance Real-Time DSP
State College, PA


----------------------------------------------------------------------
To UNSUBSCRIBE, email to [EMAIL PROTECTED]
with a subject of "unsubscribe". Trouble? Contact [EMAIL PROTECTED]

Reply via email to