有没有办法做出一种每当一个方法被调用时调用的“超级方法”,即使是非定义的方法呢?像这样排序:
public void onStart() { System.out.println("Start"); } public void onEnd() { System.out.println("End"); } public SuperMethod superMethod() { System.out.println("Super"); } // "Start" // "Super" onStart(); // "End" // "Super" onEnd(); // "Super" onRun();
感谢任何帮助.
编辑 – 细节:我有一个库更新很多,并在每次更新时重新混淆.为了使我的工作流程更简单,我使程序自动更新库(需要做我想做的,我不会那么具体说明为什么,但我的程序将与未来的更新),我有混淆映射下载与库,我想做一个名为Library的代理例如,然后当我调用Library.getInstance()时,它将获取getInstance()的模糊映射,并调用库的方法getInstance()或abz,因为它被映射到这个当前时刻.
解决方法
这是使用
Proxy类的纯Java中的一个实现:
import java.lang.reflect.*; import java.util.*; public class Demo { public static void main(String[] args) { Map<String,String> map = new HashMap<String,String>(); map.put("onStart","abc"); map.put("onEnd","def"); Library library = new LibraryProxy(map,new LibraryImpl()).proxy(); library.onStart(); library.onEnd(); library.onRun(); } } interface Library { void onStart(); void onEnd(); void onRun(); } class LibraryImpl { public void abc() { System.out.println("Start"); } public void def() { System.out.println("End"); } } class LibraryProxy implements InvocationHandler { Map<String,String> map; Object impl; public LibraryProxy(Map<String,String> map,Object impl) { this.map = map; this.impl = impl; } public Library proxy() { return (Library) Proxy.newProxyInstance(Library.class.getClassLoader(),new Class[] { Library.class },this); } @Override public Object invoke(Object proxy,Method m,Object[] args) throws Throwable { Object res = null; String name = map.get(m.getName()); if (name == null) { System.out.println("[" + m.getName() + " is not defined]"); } else { m = impl.getClass().getMethod(name,m.getParameterTypes()); res = m.invoke(impl,args); } System.out.println("super duper"); return res; } }
输出:
Start super duper End super duper [onRun is not defined] super duper