我想使用 javapoet 生成下面的代码
Javapoet 是一个自动生成 java 代码的库。
@SuppressWarnings("unchecked")
public static <T> T[] returnArrayForType(T value) {
Object array = Array.newInstance(value.getClass(), 1);
Array.set(array, 0, value);
return (T[]) array;
}
我知道如何为定义的类型编写代码,但我应该如何处理它?谁能帮忙?
最佳答案
您可以使用 TypeVariableName
。下面的片段应该让你开始。
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);
关于java - 如何使用java poet生成泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49998656/