java切面不需要接口了吗_使用java语言,如何对一个类中的静态方法做切面编程?...

展开全部

package com.classloader.test;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.lang.reflect.Modifier;

public class AOPCallStaticMehtod {

private CallBack callBack;

public AOPCallStaticMehtod(CallBack callBack) {

e5a48de588b662616964757a686964616f31333361313965this.callBack = callBack;

}

public static interface CallBack {

void before(Method method);

void after(Method method, Object result);

}

@SuppressWarnings({ "unchecked", "rawtypes" })

public Object callMethod(Class clazz, String methodName, Class[] parameterTypes, Object[] parameters) {

Object result = null;

try {

Method method = null;

if (parameterTypes == null || parameterTypes.length == 0) {

method = clazz.getMethod(methodName);

if (Modifier.isStatic(method.getModifiers())) {

callBack.before(method);

result = method.invoke(null);

callBack.after(method, result);

}else{

System.out.println("这不是一个静态方法");

}

} else {

method = clazz.getMethod(methodName, parameterTypes);

if (Modifier.isStatic(method.getModifiers())) {

callBack.before(method);

result = method.invoke(null, parameters);

callBack.after(method, result);

}else{

System.out.println("这不是一个静态方法");

}

}

} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException

| InvocationTargetException e) {

if (e instanceof NoSuchMethodException) {

System.out.println("没有这个方法");

} else {

System.out.println("call is error!");

}

}

return result;

}

public static void main(String[] args) {

CallBack callBack = new CallBack() {

@Override

public void before(Method method) {

if(method.getName().equals("test1") || method.getName().equals("test2")){

System.out.println(method.getName() + "方法在调用之前被拦截,可以在这里切面编程");

}

}

@Override

public void after(Method method, Object result) {

if(method.getName().equals("test1") || method.getName().equals("test2")){

System.out.println(method.getName() + "方法调用以后被拦截,可以在这里切面编程");

System.out.println(method.getName() + "执行结果是:" + result);

System.out.println("-----------------------------------------");

}

}

};

AOPCallStaticMehtod AOPCallStaticMehtod = new AOPCallStaticMehtod(callBack);

AOPCallStaticMehtod.callMethod(Test.class, "test1", new Class[] { String.class }, new Object[] { "ppppppppppp" });

AOPCallStaticMehtod.callMethod(Test.class, "test2", null, null);

}

}

class Test {

public static void test1(String aa) {

System.out.println(aa);

}

public static String test2() {

System.out.println("fffffffffffffffff");

return "test2 result";

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值