1919 */
2020package ch .powerunit .extensions .exceptions ;
2121
22+ import java .lang .reflect .InvocationHandler ;
2223import java .lang .reflect .InvocationTargetException ;
24+ import java .lang .reflect .Method ;
2325import java .lang .reflect .Proxy ;
2426import java .util .ArrayList ;
2527import java .util .Arrays ;
@@ -31,19 +33,27 @@ final class InternalHelper {
3133 private InternalHelper () {
3234 }
3335
34- @ SuppressWarnings ("unchecked" )
3536 public static <T extends ExceptionHandlerSupport <?, ?, ?>> T documented (T target , Supplier <String > toString ) {
37+ return proxy (target , (proxy , method , args ) -> {
38+ if (method .toString ().endsWith (".toString()" )) {
39+ return toString .get ();
40+ }
41+ return passthruInvoker (target , method , args );
42+ });
43+ }
44+
45+ private static Object passthruInvoker (Object target , Method method , Object [] args ) throws Throwable {
46+ try {
47+ return method .invoke (target , args );
48+ } catch (InvocationTargetException e ) {
49+ throw e .getCause ();
50+ }
51+ }
52+
53+ @ SuppressWarnings ("unchecked" )
54+ private static <T extends ExceptionHandlerSupport <?, ?, ?>> T proxy (T target , InvocationHandler handler ) {
3655 return (T ) Proxy .newProxyInstance (target .getClass ().getClassLoader (),
37- allInterfaces (target .getClass ()).stream ().distinct ().toArray (Class []::new ), (proxy , method , args ) -> {
38- if (method .toString ().endsWith (".toString()" )) {
39- return toString .get ();
40- }
41- try {
42- return method .invoke (target , args );
43- } catch (InvocationTargetException e ) {
44- throw e .getCause ();
45- }
46- });
56+ allInterfaces (target .getClass ()).stream ().distinct ().toArray (Class []::new ), handler );
4757 }
4858
4959 private static List <Class <?>> allInterfaces (Class <?> target ) {
0 commit comments