Вопрос

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!

Это было полезно?

Решение

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);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top