如何获得唯一的方法标识符? [英] How to get a unique method identifier?
问题描述
我需要获取一个唯一的方法标识符以用作HashMap上的键.
I'm needing to get a unique method identifier to use as a key on a HashMap.
我正在尝试使用堆栈跟踪和反射来做一些事情,并使用方法签名.但是问题是我没有找到一种方法来检索完整的方法签名(以避免方法重载).
I'm trying to do something using stacktrace and reflection and user the method signature. But the problem is I didn´t find a way to retrive the complete method signature (to avoid methods overload).
已编辑
我希望这种想法可行:
public class Class1 {
HashMap<String, Object> hm;
public Class1() {
hm = new HashMap<String, Object>();
}
public Object method() {
if (!containsKey()) {
Object value;
...
put(value);
}
return get();
}
public Object method(String arg1) {
if (!containsKey()) {
Object value;
...
put(value);
}
return get();
}
public Boolean containsKey() {
if (hm.containsKey(Util.getUniqueID(2)) {
return true;
} else {
return false;
}
}
public void put(Object value) {
hm.put(Util.getUniqueID(2), value);
}
public Object get() {
String key = Util.getUniqueID(2);
if (hm.containsKey(key) {
return hm.get(key);
} else {
return null;
}
}
}
class Util {
public static String getUniqueID(Integer depth) {
StackTraceElement element = Thread.currentThread().getStackTrace()[depth];
return element.getClassName() + ":" + element.getMethodName();
}
}
但是问题在于,采用这种策略的两种方法将具有相同的ID.
But the problem is the two methods, with this strategy, will have the same ID.
我该如何解决?
推荐答案
您可以附加+ ":" + element.getLineNumber()
,但是您仍然需要担心将两个重载方法放在一行上的情况.
You can append + ":" + element.getLineNumber()
but you'd still have to worry about the case where two overloaded methods are put on one long line.
查看StackTraceElement
方法,似乎不可能以这种方式获得唯一的方法标识符.此外,我认为该代码不太可读.
Looking at the StackTraceElement
methods, it doesn't seem possible to get a unique method identifier this way. Besides, the code is not very readable in my opinion.
我建议您尝试更明确些,然后做
I'd suggest you try to be more explicit and do
if (hm.containsKey("getValue(int)") {
...
}
或类似的东西.
这篇关于如何获得唯一的方法标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!