2021-03-04 16:15:04 -07:00
|
|
|
// reflection/SelectingMethods.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// Looking for particular methods in a dynamic proxy
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.lang.reflect.*;
|
|
|
|
|
|
|
|
class MethodSelector implements InvocationHandler {
|
|
|
|
private Object proxied;
|
2017-05-01 14:33:10 -06:00
|
|
|
MethodSelector(Object proxied) {
|
2015-06-15 17:47:35 -07:00
|
|
|
this.proxied = proxied;
|
|
|
|
}
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public Object
|
2015-06-15 17:47:35 -07:00
|
|
|
invoke(Object proxy, Method method, Object[] args)
|
|
|
|
throws Throwable {
|
|
|
|
if(method.getName().equals("interesting"))
|
2015-12-02 09:20:27 -08:00
|
|
|
System.out.println(
|
|
|
|
"Proxy detected the interesting method");
|
2015-06-15 17:47:35 -07:00
|
|
|
return method.invoke(proxied, args);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
interface SomeMethods {
|
|
|
|
void boring1();
|
|
|
|
void boring2();
|
|
|
|
void interesting(String arg);
|
|
|
|
void boring3();
|
|
|
|
}
|
|
|
|
|
|
|
|
class Implementation implements SomeMethods {
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public void boring1() {
|
2017-01-20 21:30:44 -08:00
|
|
|
System.out.println("boring1");
|
|
|
|
}
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public void boring2() {
|
2017-01-20 21:30:44 -08:00
|
|
|
System.out.println("boring2");
|
|
|
|
}
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public void interesting(String arg) {
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("interesting " + arg);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public void boring3() {
|
2017-01-20 21:30:44 -08:00
|
|
|
System.out.println("boring3");
|
|
|
|
}
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
class SelectingMethods {
|
|
|
|
public static void main(String[] args) {
|
2016-01-25 18:05:55 -08:00
|
|
|
SomeMethods proxy =
|
|
|
|
(SomeMethods)Proxy.newProxyInstance(
|
|
|
|
SomeMethods.class.getClassLoader(),
|
|
|
|
new Class[]{ SomeMethods.class },
|
|
|
|
new MethodSelector(new Implementation()));
|
2015-06-15 17:47:35 -07:00
|
|
|
proxy.boring1();
|
|
|
|
proxy.boring2();
|
|
|
|
proxy.interesting("bonobo");
|
|
|
|
proxy.boring3();
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
boring1
|
|
|
|
boring2
|
|
|
|
Proxy detected the interesting method
|
|
|
|
interesting bonobo
|
|
|
|
boring3
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|