在调用其他方法时调用方法

无论如何,在每次调用方法时都会调用一种“超级方法”,即使对于未定义的方法也是如此? 有点像:

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()的模糊映射,并在映射到at时调用库的方法getInstance()abz这个时刻。

以下是使用Proxy类的纯Java实现:

 import java.lang.reflect.*; import java.util.*; public class Demo { public static void main(String[] args) { Map map = new HashMap(); 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 map; Object impl; public LibraryProxy(Map 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 

当然你可以做到这一点,不是标准的java,而是AspectJ

这是一个简单的例子:

方面有一个后建议

 package net.fsa.aspectj.test; public aspect SuperMethdAspect { pointcut afterPointCut() : execution(public * com.my.pack.age.MyClass.*(..)); after() : afterPointCut() { System.out.println("Super"); } } 

你的目标类

 package com.my.pack.age; public class MyClass { public void onStart() { System.out.println("Start"); } public void onEnd() { System.out.println("End"); } } 

最后一些测试应用程序

 package net.fsa.aspectj.test; import com.my.pack.age.MyClass; public class MyApp { public static void main(String... args) { MyClass myClass = new MyClass(); myClass.onStart(); myClass.onEnd(); } } 

产量

 Start Super End Super 

Java并没有真正允许像这样的魔法。 为了使调用发生,它必须出现在您的(已编译)代码中。 所以答案是否定的,并非没有明确地添加对相关方法的调用。 但是,您可以通过使用预处理器或运行时代码生成来隐藏它。

我认为AspectJ可能就是你想要的。

我想这不是你想要的,但是你可以将方法中的所有代码都包装到try {}finally {supermethod ()} 。 这样就可以称之为超级方法。

这个概念背后的术语称为拦截器。 您需要一个容器来执行此操作,如ApplicationServer,CDI Container,Spring或AOP。 它的工作原理如下

 1. call your Method 2. pause your Method 3. call intercepter 4. do interceptor stuff 5. resume your Method inside the interceptor