4
4
import pl .mikigal .config .exception .InvalidConfigException ;
5
5
6
6
import java .lang .invoke .MethodHandles ;
7
- import java .lang .reflect .Constructor ;
7
+ import java .lang .reflect .Field ;
8
8
import java .lang .reflect .Method ;
9
9
import java .lang .reflect .Proxy ;
10
10
15
15
*/
16
16
public class ReflectionUtils {
17
17
18
- private static final Constructor < MethodHandles .Lookup > lookupConstructor ;
18
+ private static final MethodHandles .Lookup lookup ;
19
19
20
20
static {
21
21
try {
22
- lookupConstructor = MethodHandles .Lookup .class .getDeclaredConstructor (Class .class , Integer .TYPE );
23
- lookupConstructor .setAccessible (true );
24
- } catch (NoSuchMethodException e ) {
25
- throw new InvalidConfigException ("Could not get MethodHandles.Lookup constructor" , e );
22
+ Field field = MethodHandles .Lookup .class .getDeclaredField ("IMPL_LOOKUP" );
23
+ field .setAccessible (true );
24
+
25
+ lookup = (MethodHandles .Lookup ) field .get (null );
26
+ } catch (NoSuchFieldException | IllegalAccessException e ) {
27
+ throw new InvalidConfigException ("Could not get MethodHandles.Lookup" , e );
26
28
}
27
29
}
28
30
29
31
/**
30
32
* Allows to get default value of method from interface
31
- * @param proxy instance of proxied object
32
- * @param method method of which you want to get defalt value
33
+ * @param method method of which you want to get default value
33
34
* @return default value of method from interface
34
35
*/
35
- public static Object getDefaultValue (Object proxy , Method method ) {
36
+ public static Object getDefaultValue (Method method ) {
36
37
try {
37
38
Class <?> clazz = method .getDeclaringClass ();
38
- return lookupConstructor . newInstance ( clazz , MethodHandles . Lookup . PRIVATE )
39
+ return lookup
39
40
.in (clazz )
40
41
.unreflectSpecial (method , clazz )
41
- .bindTo (proxy )
42
+ .bindTo (createHelperProxy ( method . getDeclaringClass ()) )
42
43
.invoke ();
43
44
} catch (Throwable throwable ) {
44
45
throw new InvalidConfigException (throwable );
@@ -50,8 +51,9 @@ public static Object getDefaultValue(Object proxy, Method method) {
50
51
* @param clazz class which you want to get instance of
51
52
* @return instance of proxy
52
53
*/
53
- public static Object createHelperProxy (Class <?> clazz ) {
54
- return Proxy .newProxyInstance (clazz .getClassLoader (), new Class []{clazz }, (Object object , Method method , Object [] args ) -> null );
54
+ private static Object createHelperProxy (Class <?> clazz ) {
55
+ return Proxy .newProxyInstance (clazz .getClassLoader (), new Class []{clazz },
56
+ (Object object , Method method , Object [] args ) -> null );
55
57
}
56
58
57
59
/**
0 commit comments