java. lang.reflect. Method. Name comparison in equals (object obj)
•
Java
The following is Java in Java 7 lang.reflect. Method. Implementation of equals (object obj):
/** * Compares this {@code Method} against the specified object. Returns * true if the objects are the same. Two {@code Methods} are the same if * they were declared by the same class and have the same name * and formal parameter types and return type. */ public boolean equals(Object obj) { if (obj != null && obj instanceof Method) { Method other = (Method)obj; if ((getDeclaringClass() == other.getDeclaringClass()) && (getName() == other.getName())) { if (!returnType.equals(other.getReturnType())) return false; /* Avoid unnecessary cloning */ Class<?>[] params1 = parameterTypes; Class<?>[] params2 = other.parameterTypes; if (params1.length == params2.length) { for (int i = 0; i < params1.length; i++) { if (params1[i] != params2[i]) return false; } return true; } } } return false; }
The most interesting part here is the comparison method name: getname() = = other getName(). Those that return Java Lang. string, so a natural question is whether it is valid. Compare it by reference (= =) Although this code is obviously effective, can it become an error source in a reflection - oriented framework What's your opinion?
Solution
When you directly see the name attribute of the method class, one thing is interesting
// This is guaranteed to be interned by the VM in the 1.4 // reflection implementation private String name;
Therefore, you can directly compare and reference through interning string
More in string intern()
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码