Bonjour,
J'ai travaillé un peu avec la classe InvocationHandler qui permet de faire de l'implémentation dynamique d'une interface.
Une des illustrations classique est de créer un proxy sur un objet.
Or la classe Proxy ne permet de créer un proxy que si l'on connait les interfaces de l'objet dont on veut créer un proxy.
Je me demandais donc s'il était possible de créer de cette manière un proxy sur un objet n'implémentant pas particulièrement une interface.
Voici un petit exemple de ce que je voudrais écrire :
Avec cet exemple, l'erreur suivante se produit
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 package proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class Main { private static class MyInvocationHandler implements InvocationHandler { private Object object; public MyInvocationHandler(Object object) { this.object = object; } @Override public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable { try { System.out.println("--> " + method); return method.invoke(object, arguments); } finally { System.out.println("<-- " + method); } } } private static class MyObject { public void test() { // nothing to do. } } public static void main(String[] args) { MyObject myObject = new MyObject(); InvocationHandler handler = new MyInvocationHandler(myObject); Class<?>[] interfaces = new Class<?>[] { MyObject.class }; Object proxy = Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), interfaces, handler); ((MyObject)proxy).test(); } }Ce qui est normal puisque MyObject n'est pas une interface.Exception in thread "main" java.lang.IllegalArgumentException: proxy.Main$MyObject is not an interface
Dans ce contexte comment créer un proxy dynamique sur un objet de type MyObject ?
Partager