2

I want generate below code using javapoet

Javapoet is a library to autogenerate java code.

@SuppressWarnings("unchecked")
public static <T> T[] returnArrayForType(T value) {
    Object array = Array.newInstance(value.getClass(), 1);
    Array.set(array, 0, value);
    return (T[]) array;
}

I know how to write for defined types, but how should i deal with it? Can anyone help?

Chetan
  • 3,661
  • 6
  • 40
  • 51
  • Possible duplicate of [How to create a generic array in Java?](https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java) – daniu Apr 24 '18 at 10:03

1 Answers1

1

You can use TypeVariableName. Below snippet should get you started.

TypeVariableName typeVariable = TypeVariableName.get("T");
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("returnArrayForType")
        .addParameter(typeVariable, "value")
        .addTypeVariable(typeVariable)
        .returns(ArrayTypeName.of(typeVariable))
        .addModifiers(Modifier.PUBLIC, Modifier.STATIC);
Sukhpal Singh
  • 1,780
  • 6
  • 17