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;
}