English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Brief description
Always have been concerned about the lack of a ready-made delegation mechanism in Java, fortunately, I have had some time recently to write a simple delegation module using reflection for reference.
Module API
public Class Delegater()//Empty parameter constructor, this class manages delegation instances and implements delegation methods //Add a static method delegation and return an integer value ID representing the instance of this method and parameters. If it fails, then return-1. public synchronized int addFunctionDelegate(Class<63;> srcClass, String methodName, Object... params); //Add an instance method delegation and return an integer value ID representing the instance of this method and parameters. If it fails, then return-1. public synchronized int addFunctionDelegate(Object srcObj, String methodName, Object... params); //Delete a method delegation from the delegation instance based on an integer ID, and return whether the operation was successful public synchronized Boolean removeMethod(int registerID); //Execute all method delegations in the delegation instance in sequence (unordered) public synchronized void invokeAllMethod(); //Convert the parameter table to the parameter type table private Class<?>[] getParamTypes(Object[] params); //Obtain the method instance by the specified Class, method name, and parameter type table private Method getDstMethod(Class<?> srcClass, String methodName, Class<?>[] paramTypes); class DelegateNode(Method refMethod, Object[] params)//The DelegateNode class describes a static method delegation when not constructed with Object, including method instance and parameter table class DelegateNode(Object srcObj, Method refMethod, Object[] params)//The DelegateNode class describes an instance method delegation when constructed with Object, including class instance, method instance, and parameter table public void invokeMethod(); //Execute the method delegation described by this node
Source code
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Hashtable; /**The Delegater class implements the delegation mechanism in Java using RTTI and reflection * @author SanXiangBanZhan * */ public class Delegater { static int register = Integer.MIN_VALUE; //ID allocation variable Hashtable<Integer,DelegateNode> nodeTable; //Manage container of ID and corresponding delegate public Delegater() { nodeTable = new Hashtable<Integer,DelegateNode>(); } //Add static method delegate public synchronized int addFunctionDelegate(Class<63;> 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 delegate methods in an unordered manner public synchronized void invokeAllMethod() { for (DelegateNode node: nodeTable.values()) { node.invokeMethod(); } } //Convert the parameter table to the 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; } //Obtain a Method instance based on the instance of Class, 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 Test
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.addFunctionDelegate(DelegaterTest.class,"showCustomStaticInfo","StaticCustom!"); dele.invokeAllMethod(); dele.removeMethod(ID); System.out.println("------------------"); dele.invokeAllMethod(); } }
Execution result:
StaticCustom!
StaticDelegate!
Custom!
HelloDelegate!
------------------
StaticCustom!
StaticDelegate!
Custom!
Other matters
Some public methods use synchronized to ensure the thread safety of the register variable, so that it will not fail due to multi-threading.
For delegations with return values, a warning will be reported, but the module still accepts such delegations. However, you will not be able to get the return value when executing the delegation.
The maximum value of the added delegation is Integer.MAX_VALUE-Error handling after Integer.MIN_VALUE exceeds has not been considered (generally, there aren't that many functions that need to be delegated, right?).
Delegation execution is unordered, and when performance requirements are needed, the delegate functions should not have blocking processes, otherwise it will affect the execution of other delegate functions.
If you have any questions, you can post them here for discussion.
Summary
That's all about the detailed explanation of the delegation mechanism implementation in Java through reflection. I hope it will be helpful to everyone. Those who are interested can continue to read other Java-related topics on this site. Welcome to leave comments if there are any deficiencies. Thank you for your support to this site!
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please send an email to codebox.com (replace # with @ when sending emails) to report any violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.