Good day everyone. For example, I have only an interface, without the implementation of any class. Is it possible to create a proxy class based on this interface, without the need to create an instance of a class that implements this interface?

  • And what then will your proxy be proxying?) - fromSPb

1 answer 1

without the need to create an instance of the class that implements this interface?

The proxy class will be the class that implements the interface. The difference from the implementation of the usual class is that it is created at runtime.

Proxy :

A dynamic proxy class (below the proxy class below). A proxy interface is a proxy class interface. A proxy instance is an instance of a proxy class.

The implementation of all proxy interface methods is defined in an instance of the InvocationHandler class.

For example, I have an interface with 2 methods:

 private interface Foo { void method1(); void method2(); void method3(); } 

I want to create a proxy that implements method1 , and doesn’t do anything to everyone else (or threw an exception that the method is not implemented). This can be done, for example, as follows:

 public static void main(String... arg) { Foo foo = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), new Class[]{Foo.class}, (proxy, method, args) -> { switch (method.getName()) { case "method1": System.out.println("method1"); return null; default: break; } throw new RuntimeException(method.getName() + " is not implemented"); }); foo.method1(); foo.method2(); } 

Result of performance:

method1
Exception in thread "main" java.lang.RuntimeException: method2 is not implemented ...

  • it is! thank. I do not understand how to mark this comment with the correct answer. there is no such button - srg321
  • @ srg321 gray tick next to the answer ( i.stack.imgur.com/QpogP.png ) - Nikolay