无论如何,在每次调用方法时都会调用一种"超级方法",即使对于未定义的方法也是如此?有点像:
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();
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
编辑 - 细节:我有一个库可以更新很多,并在每次更新时进行重新模糊处理.为了使我的工作流程更容易,我正在让我的程序自动更新库(需要做我想做的事情,我不会详细说明为什么,但我的程序将使用未来的更新)并且我有混淆映射下载库,我想做一个代理调用Library的例子,然后当我调用Library.getInstance()它时,它将得到混淆映射getInstance()并调用库的方法getInstance()或者abz在当前时刻映射到它.
当然你可以这样做,不是使用标准的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");
}
}
Run Code Online (Sandbox Code Playgroud)
你的目标类
package com.my.pack.age;
public class MyClass {
public void onStart() {
System.out.println("Start");
}
public void onEnd() {
System.out.println("End");
}
}
Run Code Online (Sandbox Code Playgroud)
最后一些测试应用程序
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();
}
}
Run Code Online (Sandbox Code Playgroud)
产量
Start
Super
End
Super
Run Code Online (Sandbox Code Playgroud)
以下是使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Start
super duper
End
super duper
[onRun is not defined]
super duper
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8229 次 |
| 最近记录: |