문제

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