English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Summary
Always thought Java did not have a ready-made delegation mechanism, fortunately recently had some time, wrote a simple delegation module using reflection for reference.
Module API
public Class Delegater()//no-argument constructor, this class manages delegate instances and implements delegate methods //add a static method delegate, returning an integer value ID representing the instance of the method and the parameter. If it fails, it returns -1. public synchronized int addFunctionDelegate(Class<?> srcClass, String methodName, Object... params); //add an instance method delegate, returning an integer value ID representing the instance of the method and the parameter. If it fails, it returns -1. public synchronized int addFunctionDelegate(Object srcObj,String methodName,Object... params); //根据整型ID从委托实例中删除一个方法委托,返回是否成功 public synchronized Boolean removeMethod(int registerID); //依次执行该委托实例中的所有方法委托(无序) public synchronized void invokeAllMethod(); //将参数表转换为参数类型表 private Class<?>[] getParamTypes(Object[] params); //由指定的Class、方法名、参数类型表获得方法实例 private Method getDstMethod(Class<?> srcClass,String methodName,Class<?>[] paramTypes); class DelegateNode(Method refMethod,Object[] params)//DelegateNode类在不使用Object构造时叙述了一个静态方法委托,包括方法实例及参数表 class DelegateNode(Object srcObj,Method refMethod,Object[] params)//DelegateNode类在使用Object构造时叙述了一个实例方法委托,包括类实例、方法实例及参数表 public void invokeMethod(); //执行该节点叙述的方法委托
源代码
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Hashtable; /**Delegater类使用RTTI及反射实现Java下的委托机制 * @author 三向板砖 * */ public class Delegater { static int register = Integer.MIN_VALUE; //ID allocation variable Hashtable<Integer,DelegateNode> nodeTable; //manage the container of ID and corresponding delegation public Delegater() { nodeTable = new Hashtable<Integer,DelegateNode>(); } //add static method delegation 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 delegation 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 delegation public synchronized Boolean removeMethod(int registerID) { if(nodeTable.containsKey(registerID)) { nodeTable.remove(registerID); return true; } return false; } //unorderedly execute the delegated method public synchronized void invokeAllMethod() { for (DelegateNode node:nodeTable.values()) { node.invokeMethod(); } } //将参数表转化为参数类型表 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; } //根据Class类实例、方法名、参数类型表获得一个Method实例 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!"); } } }
اختبار الوحدة
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(); } }
نتائج التنفيذ:
StaticCustom!
StaticDelegate!
Custom!
HelloDelegate!
------------------
StaticCustom!
StaticDelegate!
Custom!
أمور أخرى
استخدام synchronized في بعض الطرق العامة العامة هو لضمان أمان متغير register، لمنع حدوث أخطاء في متعدد الأطراف.
للمعطيات التي تعود قيمًا، سيتم إصدار تحذير، ولكن يُقبل هذا التمثيل المعكوس من قبل النظام، ولكن لن يتمكنوا من الحصول على القيمة المعدة عند تنفيذ التمثيل المعكوس.
أكبر قيمة تمثيل المعكوس التي يمكن إضافتها هي Integer.MAX_VALUE - Integer.MIN_VALUE، ولا يتم النظر في معالجة الأخطاء بعد تجاوز هذا الحد (هل تحتاج حقًا إلى تمثيل معكوس لأعداد كبيرة من الوظائف؟)
تنفيذ التمثيل المعكوس غير مرتب، بالإضافة إلى ذلك، يجب تجنب استخدام العمليات المُعطلة في الوظائف المعكوسة عند الحاجة إلى أداء عالي، وإلا قد يؤثر ذلك على تنفيذ العمليات المعكوسة الأخرى.
هل هناك أي أسئلة يمكن أن تُطرح معًا للمناقشة؟
النتيجة
هذا هو محتوى المقال الكامل حول تفصيل كيفية تحقيق آلية التوليد في Java باستخدام التمثيل المعكوس، آمل أن يكون هذا مفيدًا لكم. يمكن للزوار المهتمين متابعة مواضيع أخرى المتعلقة بـ Java في هذا الموقع، وأيضًا ترحيبًا بالتعليقات التي تشير إلى نقاط الضعف. شكرًا للدعم الذي يقدمونه للواقع.
بيان: محتوى هذا المقال تم استنساخه من الإنترنت، ويتمتع ملكية حقوق النشر للمالك الأصلي، تم توفير المحتوى بواسطة المستخدمين عبر الإنترنت بشكل متعاون، ويتمتع الموقع بعدم امتلاك حقوق الملكية، ولا يتم تعديل المحتوى بشكل يدوي، ولا يتحمل الموقع أي مسؤولية قانونية. إذا كنت قد وجدت محتوى يشتبه في انتهاك حقوق النسخ، فأنت مرحب بك في إرسال بريد إلكتروني إلى: notice#oldtoolbag.com (عند إرسال البريد الإلكتروني، يرجى استبدال '#' ب '@') لإبلاغنا، وقدم الدليل اللازم، إذا تم التحقق من ذلك، سيتم حذف المحتوى المشبوه فورًا.