How to get a unique method identifier?
Asked Answered
J

1

3

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?

Jurel answered 17/10, 2014 at 12:28 Comment(2)
add the types of the arguments to your id.Hypersthene
I need a kind of singleton.Jurel
C
3

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.

Cooker answered 17/10, 2014 at 12:34 Comment(1)
The problem with element.getLineNumber() is when I use another method some lines below in the same method I get another key. I have ommited, put I would like to use a put method too. Maybe I need to have more explicit, but I would like avoid this, if is possible.Jurel

© 2022 - 2024 — McMap. All rights reserved.