2

I need to know if there is a way by which I can set the @Produces value from query parameter. For example: if the query parameter value is 'JSON' then I want to set the method header as @Produces(application/json) or if it is 'XML' then I want to set it as @Produces(application/xml)

I know that we can specify multiple media types as @Produces({"application/json", "application/xml"}), but it is not working for me as it is giving me an error when the output is JSON.

Many thanks!

sf9251
  • 268
  • 1
  • 3
  • 16
  • Possible repeat of: http://stackoverflow.com/questions/10636201/java-annotations-values-provided-in-dynamic-manner – CodeChimp Jan 10 '14 at 20:15
  • What is the error you're getting when producing JSON? Anyways, do not use `@Produces`, change the return type to `Response` as advised by @SotiriosDelimanolis in (http://stackoverflow.com/a/21053612/290799) and set the desired media type using `#type(...)`. – Michal Gajdos Jan 11 '14 at 13:26

1 Answers1

2

The Java Language Specification has rules for what can go into an annotation's attributes. Specifically, it says this

It is a compile-time error if the return type of a method declared in an annotation type is not one of the following: a primitive type, String, Class, any parameterized invocation of Class, an enum type (§8.9), an annotation type, or an array type (§10) whose element type is one of the preceding types.

Basically, annotations (and their attributes' values) are meant to be compile time constants. So, no, you cannot change the value of the annotation itself.

What you can do is follow this and make your handler method return a Response object with the appropriate media type.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724