What is the translation of this Java method signature in plain English?

269 views Asked by At

I'm porting JBox2D to Xojo. Java is not a language I know well but there are enough similarities to Xojo for this to be the easiest way to port Box2D to it.

I am well into the port but I cannot fathom the meaning of this method signature:

  public static <T> T[] reallocateBuffer(Class<T> klass, T[] oldBuffer, int oldCapacity,
      int newCapacity) {}
  1. Does this method return an array of any class type?
  2. Does Class<T> klass mean that the klass parameter can be of any class?
1

There are 1 answers

2
Thomas Tempelmann On BEST ANSWER

Basically, that function signature makes it possible to handle arrays of different types in one place. If it were programmed in C, it would probably use a macro (#define) to accomplish something similar.

Syntactically, the <T> means: T is a placeholder for any class of objecs that arr passed to this function. If you pass an object of type T to this function, then all other places that mention T inside this function will also mean that type. That way, you don't have to write separate functions if you want to handle different types. Internally, the compiler may well generate separate code for each type, though. So, generics are a shortcut, letting you work with variable types.

This will be difficult to translate into Xojo, as it doesn't provide any means for that.

Since Xojo does not offer support for Generics (Templates), you need to find out which different array types are actually used with this function, and write a specific function for each of these cases.

You may be able to work with Xojo's base class Object as the parameter, although passing arrays of Object will often not work due to Xojo's rather static type checking on arrays.

A trick around this would be to pack the array into a Variant, and then special handle each array type inside. That would still not be generic but would at least keep it all in a single function, like the original does.

Something like this:

Sub createObjects(arrayContainer as Variant, newAmount as Integer)
  if not arrayContainer.IsArray then break ' assertion

  // Handle case when array is of MyObject1
  try
    #pragma BreakOnExceptions off ' prevents Debugger from stopping here
    dim a() as MyObject1 = arrayContainer
    #pragma BreakOnExceptions default
    for i as Integer = 1 to newAmount
      a.Append new MyObject1
    next
    return
  catch exc as TypeMismatchException
    ' fall thru
  end try

  // Handle more types here
  break
End Sub

Then call it like this:

dim d() as MyObject1
createObjects d, 3