简体   繁体   中英

Java named/optional parameters using annotation?

In RESTeasy this...

@GET
@Path("request")
public String requestJson(@QueryParam("arg1") @DefaultValue("") String arg1,
                          @QueryParam("arg2") @DefaultValue("0") Integer arg2);

...allows you to define any subset of parameters defined in the method signature. Surely it is then possible to use this same pattern on any method signature something like this:

@Method
public String requestJson(@OptionalParameter("arg1") @DefaultValue("") String arg1,
                          @OptionalParameter("arg2") @DefaultValue("0") Integer arg2);

Is it possible to do this? If so how?

The annotations in the RESTEasy example are possible due to the fact that the object is managed by the RESTEasy framework. It can inspect the method and determine how to invoke it based on those annotations. It is possible to create any annotations you'd want, the key is that the code calling the method needs to know about the annotations and how to process them.

First of all, what @laz said was exactly right. This is possible in RESTEasy because RESTEasy is managing the calls to your class.

I think the pertinent question here is what you would expect an invocation of requestJson() to look like. Some examples: requestJson(1) and requestJson("String") versus something like requestJson(null, 1) and requestJson("String", null) .

There are five ways I can think of to handle this:

  1. The least automated way (but ultimately, best way): Write the variant methods yourself either by hand or set your IDE up to generate them.

  2. Make it the caller's responsibility to set the value to a default value if it doesn't have one (ie the caller determines "I'm calling a method which has a "

  3. Intercept the call to requestJson() and plugin the missing values as needed (this gets into some messy reflection or runtime code generation voodoo; it's possible, but it's not going to be simple -- basically you're building your own AOP library which will be managing all the calls to requestJson()).

  4. Plug-in to the compiler / build chain to generate the required methods, ie:

     public String requestJson() { requestJson("", 0); } public String requestJson(String arg1) { requestJson(arg1, 0); } public String requestJson(Int arg2) { requestJson("", arg2); } public String requestJson(String arg1, Int arg2) {...}

    (This is similar to what is discussed here )

  5. Add the code to determine the missing values to the top of your requestJson implementation. This would only enable things like requestJson(null, 1) , and it probably not what you are looking for (as it requires extra handing in requestJson()). It may be possible to extract the boiler plate into a library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM