java – 随时调用其他方法调用方法

前端之家收集整理的这篇文章主要介绍了java – 随时调用其他方法调用方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法做出一种每当一个方法调用调用的“超级方法”,即使是非定义的方法呢​​?像这样排序:
  1. public void onStart() {
  2. System.out.println("Start");
  3. }
  4.  
  5. public void onEnd() {
  6. System.out.println("End");
  7. }
  8.  
  9. public SuperMethod superMethod() {
  10. System.out.println("Super");
  11. }
  12.  
  13. // "Start"
  14. // "Super"
  15. onStart();
  16.  
  17. // "End"
  18. // "Super"
  19. onEnd();
  20.  
  21. // "Super"
  22. onRun();

感谢任何帮助.

编辑 – 细节:我有一个库更新很多,并在每次更新时重新混淆.为了使我的工作流程更简单,我使程序自动更新库(需要做我想做的,我不会那么具体说明为什么,但我的程序将与未来的更新),我有混淆映射下载与库,我想做一个名为Library的代理例如,然后当我调用Library.getInstance()时,它将获取getInstance()的模糊映射,并调用库的方法getInstance()或abz,因为它被映射到这个当前时刻.

解决方法

这是使用 Proxy类的纯Java中的一个实现:
  1. import java.lang.reflect.*;
  2. import java.util.*;
  3.  
  4. public class Demo
  5. {
  6. public static void main(String[] args)
  7. {
  8. Map<String,String> map = new HashMap<String,String>();
  9. map.put("onStart","abc");
  10. map.put("onEnd","def");
  11. Library library = new LibraryProxy(map,new LibraryImpl()).proxy();
  12. library.onStart();
  13. library.onEnd();
  14. library.onRun();
  15. }
  16. }
  17.  
  18. interface Library
  19. {
  20. void onStart();
  21. void onEnd();
  22. void onRun();
  23. }
  24.  
  25. class LibraryImpl
  26. {
  27. public void abc() { System.out.println("Start"); }
  28. public void def() { System.out.println("End"); }
  29. }
  30.  
  31. class LibraryProxy implements InvocationHandler
  32. {
  33. Map<String,String> map;
  34. Object impl;
  35.  
  36. public LibraryProxy(Map<String,String> map,Object impl)
  37. {
  38. this.map = map;
  39. this.impl = impl;
  40. }
  41.  
  42. public Library proxy()
  43. {
  44. return (Library) Proxy.newProxyInstance(Library.class.getClassLoader(),new Class[] { Library.class },this);
  45. }
  46.  
  47. @Override
  48. public Object invoke(Object proxy,Method m,Object[] args) throws Throwable
  49. {
  50. Object res = null;
  51. String name = map.get(m.getName());
  52. if (name == null) {
  53. System.out.println("[" + m.getName() + " is not defined]");
  54. } else {
  55. m = impl.getClass().getMethod(name,m.getParameterTypes());
  56. res = m.invoke(impl,args);
  57. }
  58. System.out.println("super duper");
  59. return res;
  60. }
  61. }

输出

  1. Start
  2. super duper
  3. End
  4. super duper
  5. [onRun is not defined]
  6. super duper

猜你在找的Java相关文章