Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

When using J/Link, how can we create an array out of objects belonging to different classes but having the same base class?

Here's an example:

partSource = 
   "org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource", "mmagraphics.png", 
part1 = JLink`JavaNew[
   "filename", partSource];
part2 = JLink`JavaNew[
   "someting", "1234"];

MakeJavaObject[{part1, part2}]

Java::excptn: A Java exception occurred: java.lang.IllegalArgumentException: array element type mismatch at java.lang.reflect.Array.set(Native Method).

I need to create a Part [] out of {part1, part2} so that I can pass it to the constructor of org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity

share|improve this question
This is for fixing the uploader palette which was broken by API changes today. – Szabolcs Apr 5 '13 at 0:14
up vote 12 down vote accepted

We can start by creating the parts using the same code as the question:

partSource = 

part1 =
    "filename", partSource];

part2 =
    "someting", "1234"];

We want to create an array whose components are of the type Part. We will need a reference to that class. A normal JLink reference is not good enough -- we need the Java object that represents the class. We use the JLink class loader to get this reference:


partClass =

We can then use the Array class to create an array of the correct type and fill in its elements:


parts =
  ReturnAsJavaObject @ Array`newInstance[partClass, 2];
Array`set[parts, 0, part1]
Array`set[parts, 1, part2]

Note carefully the use of ReturnAsJavaObject. Without it, the carefully constructed array would be immediately converted back to a Mathematica list.

We now have everything we need to construct the required MultipartRequestEntity:

post =

multipart = JavaNew[

(* JavaObject[org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity] *)
share|improve this answer
+1 for the JLinkClassLoader`classFromName[] tip. – ford Jul 24 '13 at 20:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.