Showing posts with label more than one overload matches. Show all posts
Showing posts with label more than one overload matches. Show all posts

Tuesday, October 14, 2014

Java Reflection in PeopleCode

Here is a simple example of how we can overcome the "more than one overload matches" error which occurs when calling an overloaded Java Class Method in PeopleCode.

Note: My understanding and learning is primarily based on Jim Marion's blog. This example is specific to my requirement and it can be easily extended as required.

Let us take an example of FileOutputStream class which has a write method which is overloaded.

Let us assume that we want to call the write method with the following parameters: public void write(byte[] b)

/* Use Reflection to call the appropriate method of the Java Class (which is an overloaded method) */

/* Create an instance of the Class */
Local JavaObject &fos = CreateJavaObject("java.io.FileOutputStream", "/tmp/" | &filename);

/******* REFLECTION ********/

/* Get a reference to a Java class instance of the method parameter(s): In this case the primitive byte array */
Local JavaObject &arrayClass = GetJavaClass("java.lang.reflect.Array");
Local JavaObject &bytArrClass = &arrayClass.newInstance(GetJavaClass("java.lang.Byte").TYPE, 0);

/* Get a reference to the method we want to call using Reflection */
Local JavaObject &methodArgTypes = CreateJavaObject("java.lang.Class[]", &bytArrClass.getClass());
Local JavaObject &methodReference = &fos.getClass().getMethod("write", &methodArgTypes);

/* Call the method */
Local any &result = &methodReference.invoke(&fos, CreateJavaObject("java.lang.Object[]", &byteArray));
/******* REFLECTION ********/

/* Close File Object */
&fos.close();