如何生成具有以下签名的方法?
public static <T extends MyClass & MyInterface> MyOtherClass someMethod(T type)发布于 2017-01-29 14:57:20
在这里使用TypeVariableName和addTypeVariable可能会有所帮助-
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);
}
}Note -我的MyClass、MyOtherClass和MyInterface都在一个名为com的包中,实现main()的类也驻留在这个包中。
所用进口品-
生成输出为--
包com;公共最终类GenericImpl { public静态 MyOtherClass someMethod(T类型){}
https://stackoverflow.com/questions/41916359
复制相似问题