11package me .hsgamer .topper .value .timeformat ;
22
3- import java .lang .reflect .Method ;
3+ import java .lang .invoke .MethodHandle ;
4+ import java .lang .invoke .MethodHandles ;
5+ import java .lang .invoke .MethodType ;
46
57public final class DurationTimeFormatters {
6- private static final Method FORMAT_DURATION_METHOD ;
7- private static final Method FORMAT_DURATION_WORDS_METHOD ;
8+ private static final MethodHandle FORMAT_DURATION_METHOD ;
9+ private static final MethodHandle FORMAT_DURATION_WORDS_METHOD ;
810
911 static {
1012 Class <?> clazz ;
@@ -18,22 +20,24 @@ public final class DurationTimeFormatters {
1820 }
1921 }
2022
21- Method method = null ;
23+ MethodHandles .Lookup lookup = MethodHandles .lookup ();
24+
25+ MethodHandle method = null ;
2226 if (clazz != null ) {
2327 try {
24- method = clazz . getMethod ( "formatDuration" , long .class , String .class );
25- } catch (NoSuchMethodException e ) {
28+ method = lookup . findStatic ( clazz , "formatDuration" , MethodType . methodType ( String . class , long .class , String .class ) );
29+ } catch (NoSuchMethodException | IllegalAccessException e ) {
2630 // Method not found, will return null
2731 }
2832 }
2933
3034 FORMAT_DURATION_METHOD = method ;
3135
32- Method wordsMethod = null ;
36+ MethodHandle wordsMethod = null ;
3337 if (clazz != null ) {
3438 try {
35- wordsMethod = clazz . getMethod ( "formatDurationWords" , long .class , boolean .class , boolean .class );
36- } catch (NoSuchMethodException e ) {
39+ wordsMethod = lookup . findStatic ( clazz , "formatDurationWords" , MethodType . methodType ( String . class , long .class , boolean .class , boolean .class ) );
40+ } catch (NoSuchMethodException | IllegalAccessException e ) {
3741 // Method not found, will return null
3842 }
3943 }
@@ -48,8 +52,8 @@ private DurationTimeFormatters() {
4852 public static String formatDuration (long durationMillis , String format ) {
4953 if (FORMAT_DURATION_METHOD != null ) {
5054 try {
51- return (String ) FORMAT_DURATION_METHOD .invoke ( null , durationMillis , format );
52- } catch (Exception e ) {
55+ return (String ) FORMAT_DURATION_METHOD .invokeExact ( durationMillis , format );
56+ } catch (Throwable e ) {
5357 return "INVALID FORMAT" ;
5458 }
5559 } else {
@@ -60,8 +64,8 @@ public static String formatDuration(long durationMillis, String format) {
6064 public static String formatDurationWords (long durationMillis , boolean suppressLeadingZeroElements , boolean suppressTrailingZeroElements ) {
6165 if (FORMAT_DURATION_WORDS_METHOD != null ) {
6266 try {
63- return (String ) FORMAT_DURATION_WORDS_METHOD .invoke ( null , durationMillis , suppressLeadingZeroElements , suppressTrailingZeroElements );
64- } catch (Exception e ) {
67+ return (String ) FORMAT_DURATION_WORDS_METHOD .invokeExact ( durationMillis , suppressLeadingZeroElements , suppressTrailingZeroElements );
68+ } catch (Throwable e ) {
6569 return "INVALID FORMAT" ;
6670 }
6771 } else {
0 commit comments