OnJava8-Examples/typeinfo/NullRobot.java

63 lines
1.7 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// typeinfo/NullRobot.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
// Using a dynamic proxy to create an Optional
2015-06-15 17:47:35 -07:00
import java.lang.reflect.*;
import java.util.*;
2015-12-15 11:47:04 -08:00
import java.util.stream.*;
import onjava.*;
2015-06-15 17:47:35 -07:00
class NullRobotProxyHandler implements InvocationHandler {
private String nullName;
private Robot proxied = new NRobot();
NullRobotProxyHandler(Class<? extends Robot> type) {
nullName = type.getSimpleName() + " NullRobot";
}
private class NRobot implements Null, Robot {
@Override
public String name() { return nullName; }
@Override
public String model() { return nullName; }
@Override
public List<Operation> operations() {
return Collections.emptyList();
}
}
@Override
public Object
invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return method.invoke(proxied, args);
}
}
public class NullRobot {
public static Robot
newNullRobot(Class<? extends Robot> type) {
return (Robot)Proxy.newProxyInstance(
NullRobot.class.getClassLoader(),
new Class[]{ Null.class, Robot.class },
new NullRobotProxyHandler(type));
}
public static void main(String[] args) {
2015-12-15 11:47:04 -08:00
Stream.of(
2015-06-15 17:47:35 -07:00
new SnowRemovalRobot("SnowBee"),
newNullRobot(SnowRemovalRobot.class)
2015-12-15 11:47:04 -08:00
).forEach(Robot::test);
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Robot name: SnowBee
Robot model: SnowBot Series 11
SnowBee can shovel snow
SnowBee shoveling snow
SnowBee can chip ice
SnowBee chipping ice
SnowBee can clear the roof
SnowBee clearing roof
[Null Robot]
Robot name: SnowRemovalRobot NullRobot
Robot model: SnowRemovalRobot NullRobot
2015-09-07 11:44:36 -06:00
*/