2015-09-07 11:44:36 -06:00
|
|
|
// typeinfo/SelectingMethods.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 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.
|
|
|
|
// Visit http://mindviewinc.com/Books/OnJava/ 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;
|
|
|
|
public MethodSelector(Object proxied) {
|
|
|
|
this.proxied = proxied;
|
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public Object
|
|
|
|
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 {
|
|
|
|
@Override
|
2015-11-03 12:00:44 -08:00
|
|
|
public void boring1() { System.out.println("boring1"); }
|
2015-06-15 17:47:35 -07:00
|
|
|
@Override
|
2015-11-03 12:00:44 -08:00
|
|
|
public void boring2() { System.out.println("boring2"); }
|
2015-06-15 17:47:35 -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
|
|
|
}
|
|
|
|
@Override
|
2015-11-03 12:00:44 -08:00
|
|
|
public void boring3() { 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
|
|
|
*/
|