How to get a unique method identifier?

点点圈 提交于 2020-01-04 03:49:33

问题


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).

Edited

I would like that somethink like this works:

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

But the problem is the two methods, with this strategy, will have the same ID.

How can I work around?


回答1:


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.

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)") {
    ...
}

or something similar.



来源:https://stackoverflow.com/questions/26425049/how-to-get-a-unique-method-identifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!