java 获取传入参数,Java-获取参数传递给方法?

Is it possible to get arguments pass to a method in Java using reflection api?

Is it possible to achieve this using AOP libraries like AspectJ?

I am running on Android.

public abstract class Base {

public void printArguments() {

//Here I need to get access to arg1, arg2, arg3

}

}

.

public class MyClass extends Base {

public void (String arg1, Integer arg2, String arg3) {

super.printArguments();

}

}

解决方案

Is it possible to achieve this using AOP libraries like AspectJ?

Yeah, sure. This is kind of the typical beginner's exercise in AspectJ, like so:

public class SampleClass {

public SampleClass() { super(); }

public SampleClass(String s) { this(); }

public SampleClass(int i) { this(); }

public void method01(String s, Number n, Throwable t) {}

public void method02(int i, String s, double d) {}

public void method03(String s) {}

public void method04() {}

public void method05(String s, Number n, double d) {}

public static void main(String[] args) {

new SampleClass().method01("foo", new Integer(11), new RuntimeException("error"));

new SampleClass("test").method02(11, "bar", Math.PI);

new SampleClass(123).method03("zot");

new SampleClass("another test").method04();

new SampleClass(456).method05("baz", new Integer(11), Math.E);

}

}

Now you just need to write an aspect which intercepts all your method executions (and optionally also constructor executions, as shown below):

public aspect MethodArgsAspect {

pointcut allMethods() : execution(* *(..));

pointcut allConstructors() : execution(*.new(..));

before() : !within(MethodArgsAspect) && (allMethods() || allConstructors()) {

System.out.println(thisJoinPointStaticPart.getSignature());

for (Object arg : thisJoinPoint.getArgs())

System.out.println(" " + arg);

}

}

When running SampleClass.main, this aspect will print:

void SampleClass.main(String[])

[Ljava.lang.String;@7fdcde

SampleClass()

void SampleClass.method01(String, Number, Throwable)

foo

11

java.lang.RuntimeException: error

SampleClass()

SampleClass(String)

test

void SampleClass.method02(int, String, double)

11

bar

3.141592653589793

SampleClass()

SampleClass(int)

123

void SampleClass.method03(String)

zot

SampleClass()

SampleClass(String)

another test

void SampleClass.method04()

SampleClass()

SampleClass(int)

456

void SampleClass.method05(String, Number, double)

baz

11

2.718281828459045

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值