File tree Expand file tree Collapse file tree
main/java/com/ss/rlib/common/util
test/java/com/ss/rlib/common/test/util Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -8,7 +8,7 @@ buildscript {
88 }
99}
1010
11- rootProject. version = ' 9.3 .0'
11+ rootProject. version = ' 9.4 .0'
1212group = ' com.spaceshift'
1313
1414allprojects {
Original file line number Diff line number Diff line change @@ -111,6 +111,26 @@ public static boolean isLong(@Nullable String string) {
111111 }
112112 }
113113
114+ /**
115+ * Convert a string to int object or null if this string is null or not a number.
116+ *
117+ * @param string the string to convert.
118+ * @return the int object or null.
119+ * @since 9.4.0
120+ */
121+ public static @ Nullable Integer safeToInt (@ Nullable String string ) {
122+
123+ if (string == null ) {
124+ return null ;
125+ } else {
126+ try {
127+ return Integer .valueOf (string );
128+ } catch (NumberFormatException e ) {
129+ return null ;
130+ }
131+ }
132+ }
133+
114134 /**
115135 * Convert a string to long object or null if this string is null or not a number.
116136 *
Original file line number Diff line number Diff line change @@ -40,4 +40,13 @@ void shouldConvertStringToOptionalLong() {
4040 Assertions .assertFalse (NumberUtils .toOptionalLong (null ).isPresent ());
4141 Assertions .assertFalse (NumberUtils .toOptionalLong ("2.1234" ).isPresent ());
4242 }
43+
44+ @ Test
45+ void shouldSafetyConvertStringToInt () {
46+ Assertions .assertNotNull (NumberUtils .safeToInt ("1" ));
47+ Assertions .assertNotNull (NumberUtils .safeToInt ("123124" ));
48+ Assertions .assertNull (NumberUtils .safeToInt ("notlong" ));
49+ Assertions .assertNull (NumberUtils .safeToInt (null ));
50+ Assertions .assertNull (NumberUtils .safeToInt ("2.1234" ));
51+ }
4352}
You can’t perform that action at this time.
0 commit comments