Search code examples
javajavapoet

How to add type constraints to parameterSpec for method


I'm trying to do exactly what the title says -- I'd like to generate a method spec that looks something like:

public void doSomethingWithThis( Container<? extends ImportantInterface> argument ) {
 //1. Collect UnderPants
 //2. ...
 //3. Profit
}

I understand I can just use the raw type, but generated thing will be consumed by others down stream, and having the type info pop up in their IDEs ( and mine for that matter :/ ) would make my bug solving life easier down the line...


Solution

  • So, I'm a toolbox and 7 more minutes digging around found the path to the answer. The question in the comment points in the right direction, though it's using ParameterizedTypeName.create() which is now ParameterizedTypeName.get()

    Code for sample purposes because someone else might find this useful.

    ClassName containerClassName = ClassName.get(Container.class);
    TypeName wildcardTypeName = WildcardTypeName.subtypeOf(ImportantInterface.class);
    ParameterizedTypeName parameterTypeName = ParameterizedTypeName.get(containerClassName, wildcardTypeName);
    
    classBuilder.addMethod(MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addParameter(parameterTypeName, "cargo")
            .addStatement(CodeBlock.builder()
                    .addStatement("//1. Collect Underpants")
                    .addStatement("//2. ...")
                    .addStatement("//3. Profit!!!")
                    .build())