如何修复jdeprscan检测到的BigDecimal.divide过时方法警告?
Fixing the Deprecated
BigDecimal.divide(BigDecimal, int) Warning in Your Java Code Let's break down how to resolve this deprecation warning you're seeing from jdeprscan.
First, the root cause: Java 9 marked the BigDecimal.divide(BigDecimal, int) method as deprecated because it relies on integer constants (like BigDecimal.ROUND_HALF_UP) for rounding modes. The recommended replacement is the overload that uses the RoundingMode enum, which is more type-safe and readable.
Looking at your current code:
/** * Convert duration milliseconds to seconds suitable for displaying. * * 246 milliseconds -> '0.246 secs' */ public String getDurationForDisplay() { BigDecimal duration = new BigDecimal("" + requestDuration).setScale(3); duration = duration.divide(new BigDecimal("1000"), BigDecimal.ROUND_HALF_UP); return "" + duration + " secs"; }
Step-by-Step Fix
- Replace the deprecated method call: Swap the integer rounding constant with the corresponding
RoundingModeenum value. - Import the enum if missing: Add
import java.math.RoundingMode;to the top of your class if it's not already present.
Here's the updated code:
import java.math.RoundingMode; // ... /** * Convert duration milliseconds to seconds suitable for displaying. * * 246 milliseconds -> '0.246 secs' */ public String getDurationForDisplay() { BigDecimal duration = new BigDecimal(String.valueOf(requestDuration)).setScale(3); // Use RoundingMode.HALF_UP instead of BigDecimal.ROUND_HALF_UP duration = duration.divide(new BigDecimal("1000"), RoundingMode.HALF_UP); return duration + " secs"; }
Bonus Optimizations (Cleaner, More Efficient Code)
- If
requestDurationis a numeric type (likelongorint), skip string conversion entirely:new BigDecimal(requestDuration)is more efficient than converting to a string first. - Extract the
1000value into a static constant to avoid recreating the BigDecimal object on every method call:
private static final BigDecimal MILLISECONDS_TO_SECONDS = new BigDecimal("1000"); public String getDurationForDisplay() { BigDecimal duration = new BigDecimal(requestDuration).setScale(3); duration = duration.divide(MILLISECONDS_TO_SECONDS, RoundingMode.HALF_UP); return duration + " secs"; }
After making these changes, re-run your jdeprscan command, and the deprecation warning should no longer appear.
内容的提问来源于stack exchange,提问作者Hari Sheen
相关产品推荐
相关产品推荐

