How to get string value Long.MAX_VALUE at compile time in java?

Is there any possible way to set the compile time constant using the call method at runtime? In the book Spring in Action, I got this piece of code:

private static final String MAX_LONG_AS_STRING = Long.toString(Long.MAX_VALUE); @RequestMapping(method = RequestMethod.GET) public List<Spittle> spittles( @RequestParam(value = "max", defaultValue = MAX_LONG_AS_STRING) long max, @RequestParam(value = "count", defaultValue = "20") int count) { return spittleRepository.findSpittles(max, count); } 

the problem is MAX_LONG_AS_STRING, because the defaultValue parameter must be a String constant, but MAX_LONG_AS_STRING is not a constant compile time variable, is there any possible way to get the Long max value as a constant String value? Maybe there is something that can help me call the toString method at compile time or get this value in any other way?

+6
source share
2 answers

You can achieve this, as shown in the following steps:

(1) First get the value Max long MAXVALUE = Long.MAX_VALUE;

(2) Set the value of @RequestParam as defaultValue = MAXVALUE+"" (converts long to string)

Full code:

 private static final long MAXVALUE = Long.MAX_VALUE;//Get the long value first @RequestMapping(method = RequestMethod.GET) public void spittles( @RequestParam(value = "max", defaultValue = MAXVALUE+"") long max, @RequestParam(value = "count", defaultValue = "20") int count) { // return spittleRepository.findSpittles(max, count); } 
+5
source
 private static final String MAX_LONG_AS_STRING = String.valueOf(Long.MAX_VALUE); 

could do the trick;

0
source

Source: https://habr.com/ru/post/1012448/


All Articles