Java的Object类常用方法浅解

转载:https://blog.csdn.net/xu511739113/article/details/52328727

我们知道所有的类都隐式继承Object,即Object类位于继承树最顶层,我们来看一下它的常用方法

1. finalize()

  1. /** 
  2.     * Called by the garbage collector on an object when garbage collection 
  3.     * determines that there are no more references to the object. 
  4.     * A subclass overrides the {@code finalize} method to dispose of 
  5.     * system resources or to perform other cleanup. 
  6.     * <p> 
  7.     * The general contract of {@code finalize} is that it is invoked 
  8.     * if and when the Java™ virtual 
  9.     * machine has determined that there is no longer any 
  10.     * means by which this object can be accessed by any thread that has 
  11.     * not yet died, except as a result of an action taken by the 
  12.     * finalization of some other object or class which is ready to be 
  13.     * finalized. The {@code finalize} method may take any action, including 
  14.     * making this object available again to other threads; the usual purpose 
  15.     * of {@code finalize}, however, is to perform cleanup actions before 
  16.     * the object is irrevocably discarded. For example, the finalize method 
  17.     * for an object that represents an input/output connection might perform 
  18.     * explicit I/O transactions to break the connection before the object is 
  19.     * permanently discarded. 
  20.     * <p> 
  21.     * The {@code finalize} method of class {@code Object} performs no 
  22.     * special action; it simply returns normally. Subclasses of 
  23.     * {@code Object} may override this definition. 
  24.     * <p> 
  25.     * The Java programming language does not guarantee which thread will 
  26.     * invoke the {@code finalize} method for any given object. It is 
  27.     * guaranteed, however, that the thread that invokes finalize will not 
  28.     * be holding any user-visible synchronization locks when finalize is 
  29.     * invoked. If an uncaught exception is thrown by the finalize method, 
  30.     * the exception is ignored and finalization of that object terminates. 
  31.     * <p> 
  32.     * After the {@code finalize} method has been invoked for an object, no 
  33.     * further action is taken until the Java virtual machine has again 
  34.     * determined that there is no longer any means by which this object can 
  35.     * be accessed by any thread that has not yet died, including possible 
  36.     * actions by other objects or classes which are ready to be finalized, 
  37.     * at which point the object may be discarded. 
  38.     * <p> 
  39.     * The {@code finalize} method is never invoked more than once by a Java 
  40.     * virtual machine for any given object. 
  41.     * <p> 
  42.     * Any exception thrown by the {@code finalize} method causes 
  43.     * the finalization of this object to be halted, but is otherwise 
  44.     * ignored. 
  45.     * 
  46.     * @throws Throwable the {@code Exception} raised by this method 
  47.     * @see java.lang.ref.WeakReference 
  48.     * @see java.lang.ref.PhantomReference 
  49.     * @jls 12.6 Finalization of Class Instances 
  50.     */  
  51.    protected void finalize() throws Throwable { }  
 /**
     * Called by the garbage collector on an object when garbage collection
     * determines that there are no more references to the object.
     * A subclass overrides the {@code finalize} method to dispose of
     * system resources or to perform other cleanup.
     * <p>
     * The general contract of {@code finalize} is that it is invoked
     * if and when the Java™ virtual
     * machine has determined that there is no longer any
     * means by which this object can be accessed by any thread that has
     * not yet died, except as a result of an action taken by the
     * finalization of some other object or class which is ready to be
     * finalized. The {@code finalize} method may take any action, including
     * making this object available again to other threads; the usual purpose
     * of {@code finalize}, however, is to perform cleanup actions before
     * the object is irrevocably discarded. For example, the finalize method
     * for an object that represents an input/output connection might perform
     * explicit I/O transactions to break the connection before the object is
     * permanently discarded.
     * <p>
     * The {@code finalize} method of class {@code Object} performs no
     * special action; it simply returns normally. Subclasses of
     * {@code Object} may override this definition.
     * <p>
     * The Java programming language does not guarantee which thread will
     * invoke the {@code finalize} method for any given object. It is
     * guaranteed, however, that the thread that invokes finalize will not
     * be holding any user-visible synchronization locks when finalize is
     * invoked. If an uncaught exception is thrown by the finalize method,
     * the exception is ignored and finalization of that object terminates.
     * <p>
     * After the {@code finalize} method has been invoked for an object, no
     * further action is taken until the Java virtual machine has again
     * determined that there is no longer any means by which this object can
     * be accessed by any thread that has not yet died, including possible
     * actions by other objects or classes which are ready to be finalized,
     * at which point the object may be discarded.
     * <p>
     * The {@code finalize} method is never invoked more than once by a Java
     * virtual machine for any given object.
     * <p>
     * Any exception thrown by the {@code finalize} method causes
     * the finalization of this object to be halted, but is otherwise
     * ignored.
     *
     * @throws Throwable the {@code Exception} raised by this method
     * @see java.lang.ref.WeakReference
     * @see java.lang.ref.PhantomReference
     * @jls 12.6 Finalization of Class Instances
     */
    protected void finalize() throws Throwable { }
finalize会在对象被垃圾回收时由垃圾回收器调用,垃圾对象是指没有引用指向的对象

1)JVM的垃圾回收是”最少回收”方式,只有当内存不够的时候才会进行垃圾回收

2)如果调用System.gc() 这个方法,只是告诉JVM 希望这里进行垃圾回收,但是具体什么时候回收还需要看JVM的运行状态,且System.gc()对资源还是有一定消耗,如果盲目的运用System.gc()这个方法,反而效率还会下降,看场景适用;

2.getClass()

  1. /** 
  2.      * Returns the runtime class of this {@code Object}. The returned 
  3.      * {@code Class} object is the object that is locked by {@code 
  4.      * static synchronized} methods of the represented class. 
  5.      * 
  6.      * <p><b>The actual result type is {@code Class<? extends |X|>} 
  7.      * where {@code |X|} is the erasure of the static type of the 
  8.      * expression on which {@code getClass} is called.</b> For 
  9.      * example, no cast is required in this code fragment:</p> 
  10.      * 
  11.      * <p> 
  12.      * {@code Number n = 0;                             }<br> 
  13.      * {@code Class<? extends Number> c = n.getClass(); } 
  14.      * </p> 
  15.      * 
  16.      * @return The {@code Class} object that represents the runtime 
  17.      *         class of this object. 
  18.      * @jls 15.8.2 Class Literals 
  19.      */  
  20.     public final native Class<?> getClass();  
/**
     * Returns the runtime class of this {@code Object}. The returned
     * {@code Class} object is the object that is locked by {@code
     * static synchronized} methods of the represented class.
     *
     * <p><b>The actual result type is {@code Class<? extends |X|>}
     * where {@code |X|} is the erasure of the static type of the
     * expression on which {@code getClass} is called.</b> For
     * example, no cast is required in this code fragment:</p>
     *
     * <p>
     * {@code Number n = 0;                             }<br>
     * {@code Class<? extends Number> c = n.getClass(); }
     * </p>
     *
     * @return The {@code Class} object that represents the runtime
     *         class of this object.
     * @jls 15.8.2 Class Literals
     */
    public final native Class<?> getClass();

这个方法是返回对象的实际类型,我们看个例子

  1. public class TestReflect {  
  2.       
  3.     public static void main(String[] args) {  
  4.         Object object = new Object();  
  5.         System.out.println(object.getClass());  
  6.     }  
  7. }  
public class TestReflect {

    public static void main(String[] args) {
        Object object = new Object();
        System.out.println(object.getClass());
    }
}
运行结果
  1. class java.lang.Object  
class java.lang.Object
3.equals()

  1. *  
  2.      * @param   obj   the reference object with which to compare.  
  3.      * @return  {@code trueif this object is the same as the obj  
  4.      *          argument; {@code false} otherwise.  
  5.      * @see     #hashCode()  
  6.      * @see     java.util.HashMap  
  7.      */  
  8.     public boolean equals(Object obj) {  
  9.         return (this == obj);  
  10.     }  
*
     * @param   obj   the reference object with which to compare.
     * @return  {@code true} if this object is the same as the obj
     *          argument; {@code false} otherwise.
     * @see     #hashCode()
     * @see     java.util.HashMap
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }
我们可以看到,其实在Object的equals实现其实就是用 ==  判断的其实是地址,而我们常用的一些例如String 需要判断的其实是它的值,所以说这些类肯定重写了equals方法,我们看一下源码。

  1. public final class String  
  2.     implements java.io.Serializable, Comparable<String>, CharSequence {  
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
这个是String 的代码

  1. /** 
  2.     * Compares this string to the specified object.  The result is {@code 
  3.     * true} if and only if the argument is not {@code null} and is a {@code 
  4.     * String} object that represents the same sequence of characters as this 
  5.     * object. 
  6.     * 
  7.     * @param  anObject 
  8.     *         The object to compare this {@code String} against 
  9.     * 
  10.     * @return  {@code true} if the given object represents a {@code String} 
  11.     *          equivalent to this string, {@code false} otherwise 
  12.     * 
  13.     * @see  #compareTo(String) 
  14.     * @see  #equalsIgnoreCase(String) 
  15.     */  
  16.    public boolean equals(Object anObject) {  
  17.        if (this == anObject) {  
  18.            return true;  
  19.        }  
  20.        if (anObject instanceof String) {  
  21.            String anotherString = (String)anObject;  
  22.            int n = value.length;  
  23.            if (n == anotherString.value.length) {  
  24.                char v1[] = value;  
  25.                char v2[] = anotherString.value;  
  26.                int i = 0;  
  27.                while (n– != 0) {  
  28.                    if (v1[i] != v2[i])  
  29.                        return false;  
  30.                    i++;  
  31.                }  
  32.                return true;  
  33.            }  
  34.        }  
  35.        return false;  
  36.    }  
 /**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
如果以后我们需要用equals判断值,可以重写这个方法。

3.toString()

  1. /** 
  2.      * Returns a string representation of the object. In general, the 
  3.      * {@code toString} method returns a string that 
  4.      * “textually represents” this object. The result should 
  5.      * be a concise but informative representation that is easy for a 
  6.      * person to read. 
  7.      * It is recommended that all subclasses override this method. 
  8.      * <p> 
  9.      * The {@code toString} method for class {@code Object} 
  10.      * returns a string consisting of the name of the class of which the 
  11.      * object is an instance, the at-sign character `{@code @}’, and 
  12.      * the unsigned hexadecimal representation of the hash code of the 
  13.      * object. In other words, this method returns a string equal to the 
  14.      * value of: 
  15.      * <blockquote> 
  16.      * <pre> 
  17.      * getClass().getName() + ’@’ + Integer.toHexString(hashCode()) 
  18.      * </pre></blockquote> 
  19.      * 
  20.      * @return  a string representation of the object. 
  21.      */  
  22.     public String toString() {  
  23.         return getClass().getName() + “@” + Integer.toHexString(hashCode());  
  24.     }  
/**
     * Returns a string representation of the object. In general, the
     * {@code toString} method returns a string that
     * "textually represents" this object. The result should
     * be a concise but informative representation that is easy for a
     * person to read.
     * It is recommended that all subclasses override this method.
     * <p>
     * The {@code toString} method for class {@code Object}
     * returns a string consisting of the name of the class of which the
     * object is an instance, the at-sign character `{@code @}', and
     * the unsigned hexadecimal representation of the hash code of the
     * object. In other words, this method returns a string equal to the
     * value of:
     * <blockquote>
     * <pre>
     * getClass().getName() + '@' + Integer.toHexString(hashCode())
     * </pre></blockquote>
     *
     * @return  a string representation of the object.
     */
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

返回的其实就是 类名 @ 内存地址

  1. public static void main(String[] args) {  
  2.     System.out.println(new Object().toString());  
  3. }  
public static void main(String[] args) {
    System.out.println(new Object().toString());
}
  1. 运行结果  
运行结果
  1. java.lang.Object@368102c8  
java.lang.Object@368102c8
一般的javaBean 我们都是用IDE 例如eclipse 这些工具来生成toString 来重写Object的方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值