I am reading the Proxies section in Horstmann's renowned book Core Java. I am new to this concept though. As written in the book, proxies are only necessary when you don't yet know at compile time which interfaces you need to implement. However, when you construct a proxy object, you need to supply an array of class objects which are just the interfaces to be implemented. Doesn't it sound like a self-contradiction? Please illuminate me. Thanks!
Asked
Active
Viewed 272 times
3
-
Where do you see "self-conflict" here? – PM 77-1 Feb 24 '14 at 19:38
-
If you can supply an array of interfaces to be implemented, it should mean that you already know which interfaces you need to implement. – HFanJava Feb 24 '14 at 19:44
-
When the array needs to be supplied? – PM 77-1 Feb 24 '14 at 19:46
-
`you don't yet know at compile time` and what about run-time, you'll probably know at this point. – Marc-Andre Feb 24 '14 at 19:47
-
when you create the proxy object, using Proxy.newProxyInstance(...), which is even before compilation, I am afraid. – HFanJava Feb 24 '14 at 19:48
-
A [mock framework](http://stackoverflow.com/questions/2993464/how-do-java-mocking-frameworks-work) should be a popular use case for proxies since the framework was written without knowing the classes it has to mock. – zapl Feb 24 '14 at 20:00
-
Right. The example used in the book supplied the Class[] at compile time, maybe due to the fact that it's just a toy illustration. – HFanJava Feb 24 '14 at 20:05
1 Answers
0
No, there is no self-contradiction.
This array of class objects you need to give can be dynamic, i.e. created at runtime. Typically it could be read from a configuration file where you will load the Class
object from a String
. This is typically how lot of frameworks (like Spring for the dependency injection) are working when creating proxy instance.
Adapted example from the Proxy
javadoc:
String className = readClassNameFromFile();
Class<?> myClass = Class.forName(className);
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { myClass },
handler);

LaurentG
- 11,128
- 9
- 51
- 66