Java – call other methods at any time
Is there any way to make a "super method" called every time a method is called, even if it is an undefined method? Sort like this:
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();
Thank you for any help
Edit - Details: I have a library that updates a lot and re - confuses each update In order to make my workflow simpler, I make the program automatically update the library (I need to do what I want to do, I won't specify why, but my program will be updated in the future). I have confused mapping, downloading and library. I want to be an agent called library, for example, and then when I call library When getInstance (), it will get the fuzzy mapping of getInstance () and call the library method getInstance () or ABZ, because it is mapped to the current time
Solution
This is an implementation in pure java using the proxy class:
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; } }
Output:
Start super duper End super duper [onRun is not defined] super duper