krkonop krkonop - 21 days ago 5
Java Question

How to retrive string value of Long.MAX_VALUE in compile time in java?

Is there any possible way to setup constant compile time value using a runtime call method?
In "Spring in Action" book, 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 with MAX_LONG_AS_STRING, because defaultValue param needs to be a String constant but MAX_LONG_AS_STRING is not a constant compile time variable, is there any possible way to get Long max value as a constant String value?
Maybe there is something which can help me to call toString method during compile time, or retrieve this value in any other way ?

Answer

You can achieve this as shown in the below steps:

(1) Get the Max value first long MAXVALUE = Long.MAX_VALUE;

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

Complete 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);
    }