62 lines
1.7 KiB
Java
Raw Permalink Normal View History

// reflection/NullRobot.java
// (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
// 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 {
2015-06-15 17:47:35 -07:00
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() {
2015-06-15 17:47:35 -07:00
return Collections.emptyList();
}
}
@Override public Object
2015-06-15 17:47:35 -07:00
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(
new SnowRobot("SnowBee"),
newNullRobot(SnowRobot.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: SnowRobot NullRobot
Robot model: SnowRobot NullRobot
2015-09-07 11:44:36 -06:00
*/