How would I generate a method with the following signature?
public static <T extends MyClass & MyInterface> MyOtherClass someMethod(T type)
How would I generate a method with the following signature?
public static <T extends MyClass & MyInterface> MyOtherClass someMethod(T type)
在这里使用TypeVariableName
withaddTypeVariable
可能会有所帮助 -
import com.squareup.javapoet.*;
import javax.lang.model.element.Modifier;
import java.io.IOException;
public class AttemptGeneric {
public static void main(String[] args) throws IOException {
ClassName myClass = ClassName.get("com", "MyClass");
ClassName myOtherClass = ClassName.get("com", "MyOtherClass");
ClassName myInterface = ClassName.get("com", "MyInterface");
TypeVariableName typeVariableName = TypeVariableName.get("T", myClass);
MethodSpec methodSpec = MethodSpec.methodBuilder("someMethod")
.returns(myOtherClass)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addTypeVariable(typeVariableName.withBounds(myInterface))
.addParameter(typeVariableName,"type")
.build();
TypeSpec genericClass = TypeSpec.classBuilder("GenericImpl")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(methodSpec)
.build();
JavaFile javaFile = JavaFile.builder("com", genericClass)
.build();
javaFile.writeTo(System.out);
}
}
注意- 我有我的MyClass
,MyOtherClass
并且MyInterface
都在一个名为的包com
也是实现它的类main()
所在的位置。
使用的进口 -
生成输出为 -
package com; public final class GenericImpl { public static <T extends MyClass & MyInterface> MyOtherClass someMethod(T type) { } }