Java 添加泛型参数

Java 添加泛型参数,java,code-generation,javapoet,Java,Code Generation,Javapoet,如何生成具有以下签名的方法 public <T extends MyClass> void doSomething(T t) 编辑这是上面代码生成的内容(我不知道如何添加参数): public void doSomething() 将生成的TypeVariableName提取到变量中,以便重用其值 TypeVariableName typeVariableName = TypeVariableName.get("T", MyClass.class); 然后添加该类型的参数 Met

如何生成具有以下签名的方法

public <T extends MyClass> void doSomething(T t)
编辑这是上面代码生成的内容(我不知道如何添加参数):

public void doSomething()

将生成的
TypeVariableName
提取到变量中,以便重用其值

TypeVariableName typeVariableName = TypeVariableName.get("T", MyClass.class);
然后添加该类型的参数

MethodSpec spec = MethodSpec.methodBuilder("doSomething")
                            .addModifiers(Modifier.PUBLIC)
                            .addTypeVariable(typeVariableName)
                            .addParameter(typeVariableName, "t") // you can also add modifiers
                            .build();

如果要传递泛型类型结构,请使用以下方法

MethodSpec loadListInteger = MethodSpec.methodBuilder("loadListInteger")
                    .addModifiers(Modifier.PUBLIC)
                    .returns(void.class)
                    .addParameter(ParameterizedTypeName.get(List.class, Integer.class), "list")
                    .build();
MethodSpec spec = MethodSpec.methodBuilder("doSomething")
                            .addModifiers(Modifier.PUBLIC)
                            .addTypeVariable(typeVariableName)
                            .addParameter(typeVariableName, "t") // you can also add modifiers
                            .build();
MethodSpec loadListInteger = MethodSpec.methodBuilder("loadListInteger")
                    .addModifiers(Modifier.PUBLIC)
                    .returns(void.class)
                    .addParameter(ParameterizedTypeName.get(List.class, Integer.class), "list")
                    .build();