java反射调用无参数方法_java – 在没有反射的情况下识别调用方法和参数

Is that possible without reflection?

不.(我甚至认为反射是不可能的.)

Are there any design pattern that needs to be followed?

这里的模式是将相关信息作为参数传递给方法. 🙂

您还可以将Child的实例传递给Parent的构造函数,并将URL存储为Child中的字段.

Parent parent = new Parent(this); // ...then look up URL through field in Child

或者,您可以在调用isValidURL之前使用setter:

public void verifyURL(String url) {

parent.setUrl(url);

parent.isValidURL();

}

关于你的编辑:

EDIT: I want to do this because I want to implement the idea on a logger. Basically, there are many other methods like verifyURL() method accepting different parameters. I’d like to have a common logger to print the it on the console when any methods in the `Child’ class is called

这清除了很多东西.

为此,我建议查看当前的堆栈跟踪.我在这里发布了类似的解决方案:

要记住稳健性,重要的是循环遍历堆栈跟踪,直到找到您要查找的元素.尽管Parent可以在内部委托调用或使用isValidUrl作为辅助方法,但很可能是感兴趣的调用类(在本例中为Child).这是一个丢弃“内部”堆栈元素并打印调用类/方法名称的示例:

public boolean isValidURL() {

for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {

if (ste.getClassName().equals(Thread.class.getName())

|| ste.getClassName().equals(getClass().getName()))

continue;

System.out.println(ste.getClassName() + "." + ste.getMethodName());

break;

}

return true;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值