Brief description
I have always been worried about Java's lack of ready-made delegation mechanism. Fortunately, I have some time recently, and wrote a simple delegation module with reflection for reference.
Module API
public Class Delegater()//Empty parameter construction, this class manages the delegate instance and implements the delegate method //Add a static method delegate, and returns the integer value ID to represent the instance composed of the method and parameters. If it fails, return -1. public synchronized int addFunctionDelegate(Class<?> srcClass,String methodName,Object... params);//Add an instance method delegate, return the integer value ID to represent the instance composed of the method and parameters. If it fails, return -1. public synchronized int addFunctionDelegate(Object srcObj,String methodName,Object... params);//Delete a method delegate from the delegate instance based on the integer ID and return whether it is successful public synchronized Boolean removeMethod(int registerID);//Execute all method delegates in this delegate instance in sequence (unordered) public synchronized void invokeAllMethod();//Convert the parameter table to parameter type table private Class<?>[] getParamTypes(Object[] params);//Get the method instance private Method from the specified Class, method name, and parameter type table private Method getDstMethod(Class<?> srcClass,String methodName,Class<?>[] paramTypes);class DelegateNode(Method refMethod,Object[] params)//DelegateNode class describes a static method delegation when not using Object construction, including method instances and parameter tables. class DelegateNode(Object srcObj,Method refMethod,Object[] params)//DelegateNode class describes an instance method delegation when using Object construction, including class instances, method instances and parameter tables public void invokeMethod();//The method delegation that executes the node description is
source code
import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.Hashtable;/**Delegater class uses RTTI and reflection to implement the delegate mechanism in Java* @author Three-way brick* */public class Delegater {static int register = Integer.MIN_VALUE;//ID allocation variable Hashtable<Integer,DelegateNode> nodeTable;//Manage ID and the container of the corresponding delegate public Delegater() {nodeTable = new Hashtable<Integer,DelegateNode>();}//Add static method delegate public synchronized int addFunctionDelegate(Class<?> srcClass,String methodName,Object... params) {Class<?>[] paramTypes = getParamTypes(params);Method refMethod;if((refMethod = getDstMethod(srcClass,methodName,paramTypes)) != null) {register++;nodeTable.put(register,new DelegateNode(refMethod, params));return register;} else {return -1;}}//Add dynamic method delegate public synchronized int addFunctionDelegate(Object srcObj,String methodName,Object... params) {Class<?>[] paramTypes = getParamTypes(params);Method refMethod;if((refMethod = getDstMethod(srcObj.getClass(), methodName,paramTypes)) != null) {register++;nodeTable.put(register,new DelegateNode(srcObj,refMethod, params));return register;} else {return -1;}}//Delete a method delegate public synchronized Boolean removeMethod(int registerID) {if(nodeTable.containsKey(registerID)) {nodeTable.remove(registerID);return true;}return false;}//Execute the delegate method unorderedly public synchronized void invokeAllMethod() {for (DelegateNode node:nodeTable.values()) {node.invokeMethod();}}//Convert the parameter table into a parameter type table private Class<?>[] getParamTypes(Object[] params) {Class<?>[] paramTypes = new Class<?>[params.length];for (int i = 0;i < params.length;i++) {paramTypes[i] = params[i].getClass();}return paramTypes;}//Get a Method instance based on Class class instance, method name, and parameter type table private Method getDstMethod(Class<?> srcClass,String methodName,Class<?>[] paramTypes) {Method result = null;try {result = srcClass.getMethod(methodName, paramTypes);if(result.getReturnType() != void.class) {System.out.println("Warning,Method:"+methodName+" has a return value!");}}catch (NoSuchMethodException | SecurityException e) {System.out.println("Can Not Found Method:"+methodName+",ensure it's exist and visible!");}return result;}}class DelegateNode {Object srcObj;Method refMethod;Object[] params;public DelegateNode(Method refMethod,Object[] params) {this.refMethod = refMethod; this.params = params;}public DelegateNode(Object srcObj,Method refMethod,Object[] params) {this.srcObj = srcObj; this.refMethod = refMethod; this.params = params;}public void invokeMethod() {try {refMethod.invoke(srcObj,params);}catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {System.out.println("Method:"+refMethod.toString()+" invoke fail!");}}}Module testing
public class DelegaterTest {public void showInfo() {System.out.println("Hello Delegate!");}public void showCustomInfo(String info) {System.out.println(info);}public static void showStaticInfo() {System.out.println("Static Delegate!");}public static void showCustomStaticInfo(String info) {System.out.println(info);}public static void main(String[] args) {Delegater dele = new Delegater();DelegaterTest tester = new DelegaterTest();int ID = dele.addFunctionDelegate(tester,"showInfo");dele.addFunctionDelegate(tester,"showCustomInfo","Custom!");dele.addFunctionDelegate(DelegaterTest.class,"showStaticInfo");dele.addFuncti onDelegate(DelegaterTest.class,"showCustomStaticInfo","StaticCustom!");dele.invokeAllMethod();dele.removeMethod(ID);System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Execution results:
StaticCustom!
StaticDelegate!
Custom!
HelloDelegate!
------------------
StaticCustom!
StaticDelegate!
Custom!
Other matters
Some public methods use synchronized to ensure the thread safety of register variables so that they will not make mistakes due to multiple threads.
A warning will be issued for delegates with return values, but the module still accepts such delegations, but you will not get the return value when executing the delegation.
The maximum value of the added delegate is the fault tolerance process after Integer.MAX_VALUE-Integer.MIN_VALUE is not considered (generally there are not so many functions that require delegate.
Delegated execution is disordered, and when performance requirements are required, try not to block the delegated function, otherwise it will affect the execution of other delegated functions.
Any other questions can be posted to discuss.
Summarize
The above is all the detailed explanation of this article about implementing the delegate mechanism code in Java through reflection. I hope it will be helpful to everyone. Interested friends can continue to refer to other Java-related topics on this website. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!