Skip to content

Allow @Spec on method parameters for method-based subcommands#2509

Open
EmperorSARATH wants to merge 1 commit intoremkop:mainfrom
EmperorSARATH:feature/spec-method-param
Open

Allow @Spec on method parameters for method-based subcommands#2509
EmperorSARATH wants to merge 1 commit intoremkop:mainfrom
EmperorSARATH:feature/spec-method-param

Conversation

@EmperorSARATH
Copy link
Copy Markdown

@EmperorSARATH EmperorSARATH commented Apr 3, 2026

This PR addresses issue #1670 by allowing @Spec to be used on method parameters in method-based subcommands.

Changes:

  • Added ElementType.PARAMETER to @Spec to enable usage on method parameters.
  • Inject the correct CommandSpec via commandMethodParamValues() for method subcommands.
  • Prevent @Spec parameters from being treated as CLI arguments.
  • Scoped the change to method parameters to avoid affecting existing behavior.
  • Verified that all existing tests pass.

Motivation:

Previously, method-based subcommands could not directly receive a CommandSpec via a parameter, forcing developers to use fragile workarounds like looking up the subcommand from the parent spec. This PR provides a clean and safe way to inject the subcommand's CommandSpec.

Example usage:

import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Spec;
import picocli.CommandLine.Model.CommandSpec;

@Command(name = "app", subcommands = {TestApp.class})
public class TestApp {

    public static void main(String[] args) {
        CommandLine cmd = new CommandLine(new TestApp());
        cmd.execute(args);
    }

    @Command(name = "sub")
    void sub(@Spec CommandSpec spec) {
        System.out.println("Subcommand name: " + spec.name());
    }
}

Example run :

$ java -cp .:build/libs/picocli-4.7.8-SNAPSHOT.jar TestApp sub
Subcommand name: sub

Fixes: #1670

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

allow a @Spec CommandSpec parameter to methods that define a subcommand

1 participant