java.lang.reflect.Method.equals(Object obj)中的名称比较
发布时间:2020-09-25 06:07:43  所属栏目:Java  来源:互联网 
            导读:以下是 Java 7中java.lang.reflect.Method.equals(Object obj)的实现: /** * Compares this {@code Method} against the specified object. Returns * true if the objects are the same. Two {@code Methods} are the
                
                
                
            | 
                         以下是 Java 7中java.lang.reflect.Method.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;
} 
 这里最有趣的部分是比较方法名称:getName()== other.getName().那些返回java.lang.String,因此一个自然的问题是它是否有效通过引用(==)进行比较.虽然这个代码显然是有效的,但是它是否可以成为面向反射的框架中的错误源.你怎么看? 解决方法当你直接看到Method类的name属性时,有一件事情是有趣的.// This is guaranteed to be interned by the VM in the 1.4 // reflection implementation private String name; 所以通过interning String你可以直接比较参考. 更多在String.intern() (编辑:莱芜站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
相关内容
- java中将科学计数法转换普通计数法的简单方法
 - JavaBean和Map转换封装类的方法
 - java – 如何从流中获取随机对象
 - java – 区分String args []和String [] args
 - Java OutOfMemory异常:加载zip文件时出现mmap错误
 - 浅谈java中的TreeMap 排序与TreeSet 排序
 - java – 为什么我的JVM做一些运行时循环优化,并使我的代码b
 - Java SAXParser:不同于`localName`和`qName`
 - java – 从log4j.Logger获取getLogger的一般方式
 - java – 返回带Jersey的String的JSON表示形式
 
