2

In the whole jvm run life, is the Method class instance always unique? for example, I have a class which implements InvocationHandler. In method invoke, which has a Method parameter. I know all methods that i can handle, and I want to use different strategy to handle different method. So I build a strategy map like Map. codes like:

@Override public Object invoke(Object proxy, Method method, Object[] args)  throws Throwable {
    Strategy strategy = strategyMap.get(method);
    Method realMethod = strategy.getCorrespondingMethod();
    return realMethod.invoke(this, args); 
}

The question is IF i use this strategy, the Method object MUST be global unique in the whole JVM running life. Otherwise, i cannot find the correct strategy.

So, Is the instance of Method class in java is global unique.

Question 2: How about the efficient of Method:toGenericString(), i the use method object cannot accomplish this job, i think i can use method generic string.

Thank you.

CodeBoy
  • 591
  • 6
  • 12

1 Answers1

3

You should see it in this way - for a given class, the method instance is always unique. The reason I added for a given class is because 2 same classes loaded using different class loaders will have different instances of the same method.

How about the efficient of Method:toGenericString()

Well, efficiency is a relative concept. You have nothing against which toGenericString() can be compared. So, if toGenericString() does the job, go for it and forget about the efficiency :P

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • i agree the answer for q2. About q1, is that possible if one Class may be have different class loader???? cannot believe – CodeBoy Apr 10 '15 at 06:22
  • Or A a, A b: a and b is two object Of class A. Is that possible a.class.getClassLoader() is different of b.class.getClassLoader()???? – CodeBoy Apr 10 '15 at 06:26
  • @CodeBoy - Yes. If you use 2 different class loaders to load 2 different classes then they will be different :) – TheLostMind Apr 10 '15 at 06:27
  • thank you. And In what situation, there will be two class loader for one class. – CodeBoy Apr 10 '15 at 06:36
  • 1
    @CodeBoy - You can load a class twice using 2 different class loaders. Any situation which loads a class twice is usually *bad* and might lead to *side-effects* that cannot be usually forseen :P – TheLostMind Apr 10 '15 at 06:39