kohsuke / args4j

args4j
http://args4j.kohsuke.org/
MIT License
789 stars 189 forks source link

If subcommands are used and parsing fails, how to know which sub-command was selected #142

Open xpromache opened 7 years ago

xpromache commented 7 years ago

If I use sub-commands and the parsing fails (for example because a required option in sub-command was missing), how do I know which sub-command has been selected? I need that in order to print the usage for that specific sub-command. The current sub-command handler looks to be available in CmdLineParser.currentOptionHandler but there is no getter for that field.

apj68 commented 6 years ago

The original annotated field (which had the subCommand annotation) should have the value of the implementation class. In that case, just pull up that field of your options class and you should be able to see. If it's null then it's possible the field access modifier restricted args4j from updating it. The reason I ran across your issue here is because I was trying to do the same thing and my annotated field was null. I had to debug it and discovered that if accessibility is restricted and the field is made accessible via f.setAccessibility(true) then, ymmv. From Field javadoc:

If this Field object is enforcing Java language access control, and the underlying field is inaccessible, the method throws an IllegalAccessException.

If the underlying field is final, the method throws an IllegalAccessException unless setAccessible(true) has succeeded for this Field object and the field is non-static. Setting a final field in this way is meaningful only during deserialization or reconstruction of instances of classes with blank final fields, before they are made available for access by other parts of a program. Use in any other context may have unpredictable effects, including cases in which other parts of a program continue to use the original value of this field.

But anyhow, in your case (and I know this issue is ancient) you should just be able to check your options class.