OnJava8-Examples/typeinfo/SelectingMethods.java

60 lines
1.5 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: typeinfo/SelectingMethods.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
// Looking for particular methods in a dynamic proxy.
import java.lang.reflect.*;
import static net.mindview.util.Print.*;
class MethodSelector implements InvocationHandler {
private Object proxied;
public MethodSelector(Object proxied) {
this.proxied = proxied;
}
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public Object
invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(method.getName().equals("interesting"))
print("Proxy detected the interesting method");
return method.invoke(proxied, args);
}
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
interface SomeMethods {
void boring1();
void boring2();
void interesting(String arg);
void boring3();
}
class Implementation implements SomeMethods {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public void boring1() { print("boring1"); }
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public void boring2() { print("boring2"); }
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public void interesting(String arg) {
print("interesting " + arg);
}
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public void boring3() { print("boring3"); }
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
class SelectingMethods {
public static void main(String[] args) {
SomeMethods proxy= (SomeMethods)Proxy.newProxyInstance(
SomeMethods.class.getClassLoader(),
new Class[]{ SomeMethods.class },
new MethodSelector(new Implementation()));
proxy.boring1();
proxy.boring2();
proxy.interesting("bonobo");
proxy.boring3();
}
} /* Output:
boring1
boring2
Proxy detected the interesting method
interesting bonobo
boring3
*///:~