[Java SE] dynamic proxy + empty object implementation, javase
Import java. lang. reflect. invocationHandler; import java. lang. reflect. method; import java. lang. reflect. proxy; import java. util. arrays; import java. util. collections; import java. util. list; public class NullRobot {public static void main (String [] args) {// 1 Robot r = newNullRobot (); if (Null. class. isInstance (r) {// if (r instanceof Null) {// another way System. out. println ("[NullRobot]");} System. out. println (R. name (); List <strong> l = r. ops (); for (condition failed: l) {System. out. println (bytes. comm ();} // 2 Robot r2 = (Robot) new NullRobotProxyHandler (). bind (null); if (Null. class. isInstance (r2) {System. out. println ("[NullRobot]");} System. out. println (r2.name (); List <latency> l2 = r2.ops (); for (latency encoding: l2) {System. out. println (bytes. comm () ;}} public static Robot newNullRobot () {return (Robot) Proxy. ne WProxyInstance (NullRobot. class. getClassLoader (), // What can be passed in by classLoader? The classLoader that meets certain conditions can be used to load the proxy Class new Class [] {Robot. class, Null. class}, new NullRobotProxyHandler ();} interface Null {} class NullRobotProxyHandler implements InvocationHandler {// Robot proxied = class NRobot implements Robot, Null // In fact, you can not inherit the Null interface, as long as Proxy. class [] In newProxyInstance () contains Null. class to make instanceof true {private String name = "NoneName"; @ Override public String name () {// TODO Auto-generated method stub return name ;} @ Override public List <strong> ops () {// TODO Auto-generated method stub return Collections. emptyList () ;}}// === another bind way binding real obj with proxy public Object bind (Object realObj) {realObj = new NRobot (); return (Robot) Proxy. newProxyInstance (realObj. getClass (). getClassLoader (), realObj. getClass (). getInterfaces (), this) ;}@ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {// TODO Auto-generated method stub return method. invoke (new NRobot (), args) ;}} interface handler {String comm () ;}interface Robot {String name (); List