假设我有一个类如下所示的方法
public class Parent {
public boolean isValidURL() {
System.out.println("print the name of the caller method and the method's arguements here");
//pls ignore the return true below. just an eg.
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有另一个方法调用父类中的isValidURL
public class Child {
Parent parent = new Parent();
public void verifyURL(String url) {
parent.isValidURL();
}
}
Run Code Online (Sandbox Code Playgroud)
现在在Parent类中,该方法isValidURL()应该打印调用方法verifyURL()及其参数.
没有反思可能吗?是否有需要遵循的设计模式?
编辑:我想这样做,因为我想在记录器上实现这个想法.基本上,还有许多其他方法,例如verifyURL()接受不同参数的方法.当调用`Child'类中的任何方法时,我想有一个通用记录器在控制台上打印它
没有反思可能吗?
号(我甚至不认为这是可能与反思.)
是否有需要遵循的设计模式?
这里的模式是将相关信息作为参数传递给方法.:-)
您还可以将该实例传递Child给该构造函数Parent,并将该URL存储为字段Child.
Parent parent = new Parent(this); // ...then look up URL through field in Child
Run Code Online (Sandbox Code Playgroud)
或者,您可以在调用之前使用setter isValidURL:
public void verifyURL(String url) {
parent.setUrl(url);
parent.isValidURL();
}
Run Code Online (Sandbox Code Playgroud)
关于你的编辑:
编辑:我想这样做,因为我想在记录器上实现这个想法.基本上,还有许多其他方法,如verifyURL()方法接受不同的参数.当调用`Child'类中的任何方法时,我想有一个通用记录器在控制台上打印它
这清除了很多东西.
为此,我建议查看当前的堆栈跟踪.我在这里发布了类似的解决方案:
要记住稳健性,重要的是循环遍历堆栈跟踪,直到找到您要查找的元素.即使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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
676 次 |
| 最近记录: |