>>>>> Daniel Dulitz writes:
Daniel> 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.
Daniel> You "just" use the standard ways to call Java methods from
Daniel> JNI code. :-)
Daniel> Call Class.forName(String) to get an Object that
Daniel> corresponds to the class you want to allocate. Then call
Daniel> getDeclaredConstructors() on that object; that will return
Daniel> an array of objects having type Constructor. Search
Daniel> through that array until you find the Constructor of four
Daniel> arguments that you want. Finally, call newInstance() on
Daniel> that Constructor object, passing it array of type Object
Daniel> that contains each of the arguments you want to pass.
Daniel> That's really complicated, so there are a few ways to
Daniel> cheat. Let NativeClass be the class containing your
Daniel> native method, let TargetClass be the class you want your
Daniel> native method to instantiate, and assume that you want to
Daniel> run the following constructor: public TargetClass (int n,
Daniel> double d, String s, Vector v) { ... }
Daniel> Then you can use a static initializer to find the
Daniel> constructor you want and assign it to a static member
Daniel> variable.
Daniel> package com.foobar;
Daniel> public class NativeClass {
Daniel> static Constructor cons;
Daniel> static {
Daniel> final Class cTarget = Class.forName ("com.foobar.TargetClass");
Daniel> final Class cStr = Class.forName ("java.lang.String");
Daniel> final Class cVec = Class.forName ("java.lang.Vector");
Daniel> cons = c.getConstructor
Daniel> (new Class [] { Integer.TYPE, Double.TYPE, cStr, cVec });
Daniel> }
Daniel> // ...
Daniel> // various native method declarations here
Daniel> }
Daniel> Now all your JNI code has to do is get the static field
Daniel> named "cons", create an Object [] containing the arguments
Daniel> to the constructor, and call the newInstance(Object [])
Daniel> method.
I may miss the point but why don't you use something like
jclass myclz = env->FindClass("com/foobar/TargetClass");
jmethodID cons = env->GetMethodID(myclz, "<init>",
"(IDLjava/lang/String;Ljava/util/Vector;)V");
jobject obj = env->NewObject(myclz, cons, myint, mydouble, myString, myVector);
Juergen
--
Juergen Kreileder, Universitaet Dortmund, Lehrstuhl Informatik V
Baroper Strasse 301, D-44221 Dortmund, Germany
Phone: ++49 231/755-5806, Fax: ++49 231/755-5802
----------------------------------------------------------------------
To UNSUBSCRIBE, email to [EMAIL PROTECTED]
with a subject of "unsubscribe". Trouble? Contact [EMAIL PROTECTED]