回顾JavaSE(1)-API、Object(hashCode、getClass)

来源:互联网 发布:好的java培训机构 编辑:程序博客网 时间:2024/06/06 00:17

Java API说白了就是JDK提供给我们简化编程的东西。

API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。

编写一个机器人程序去控制机器人踢足球,程序就需要向机器人发出向前跑、向后跑、射门、抢球等各种命令,没有编过程序的人很难想象这样的程序如何编写。但是对于有经验的开发人员来说,知道机器人厂商一定会提供一些用于控制机器人的Java类,这些类中定义好了操作机器人各种动作的方法。其实,这些Java类就是机器人厂商提供给应用程序编程的接口,大家把这些类称为Xxx Robot API。


我们先来看最基本的类Object,最好的学习材料-官方API,这里提供一个我的API云盘链接,请叫我红领巾。

百度云链接:https://pan.baidu.com/s/1pLLCzbX


java.lang.Object

Since:JDK1.0 

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.

构造方法:publicObject()
因此面向对象:子类的构造方法默认访问的是父类的无参构造方法

我们先看它的hashCode():
inthashCode()
Returns a hash code value for the object.

  • public int hashCode()
    Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided byHashMap.

    The general contract of hashCode is:

    • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
    • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
    • It is not required that if two objects are unequal according to theequals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

    As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

    Returns:
    a hash code value for this object.
    See Also:
    equals(java.lang.Object),System.identityHashCode(java.lang.Object)
哈希值由哈希算法基于地址值计算,并非地址值。

测试代码:

public class hashCodeTest {/** * 权兴权意-20160907 * @param args */public static void main(String[] args) {// TODO Auto-generated method stubEmployee e1 = new Employee();Employee e2 = new Employee();System.out.println(e1.hashCode());//1021653256System.out.println(e2.hashCode());//1794515827Employee e3 = e1;System.out.println(e3.hashCode());//1021653256}}public class Employee {}


内部实现:

    /**     * Returns a hash code value for the object. This method is      * supported for the benefit of hashtables such as those provided by      * <code>java.util.Hashtable</code>.      * <p>     * The general contract of <code>hashCode</code> is:      * <ul>     * <li>Whenever it is invoked on the same object more than once during      *     an execution of a Java application, the <tt>hashCode</tt> method      *     must consistently return the same integer, provided no information      *     used in <tt>equals</tt> comparisons on the object is modified.     *     This integer need not remain consistent from one execution of an     *     application to another execution of the same application.      * <li>If two objects are equal according to the <tt>equals(Object)</tt>     *     method, then calling the <code>hashCode</code> method on each of      *     the two objects must produce the same integer result.      * <li>It is <em>not</em> required that if two objects are unequal      *     according to the {@link java.lang.Object#equals(java.lang.Object)}      *     method, then calling the <tt>hashCode</tt> method on each of the      *     two objects must produce distinct integer results.  However, the      *     programmer should be aware that producing distinct integer results      *     for unequal objects may improve the performance of hashtables.     * </ul>     * <p>     * As much as is reasonably practical, the hashCode method defined by      * class <tt>Object</tt> does return distinct integers for distinct      * objects. (This is typically implemented by converting the internal      * address of the object into an integer, but this implementation      * technique is not required by the      * Java<font size="-2"><sup>TM</sup></font> programming language.)     *     * @return  a hash code value for this object.     * @see     java.lang.Object#equals(java.lang.Object)     * @see     java.util.Hashtable     */    public native int hashCode();


现在看看getClass():

Class<?>getClass()

Returns the runtime class of thisObject.

  • public final Class<?> getClass()
    Returns the runtime class of thisObject. The returnedClass object is the object that is locked bystatic synchronized methods of the represented class.

    The actual result type is Class<? extends |X|> where|X| is the erasure of the static type of the expression on whichgetClass is called. For example, no cast is required in this code fragment:

    Number n = 0;
    Class<? extends Number> c = n.getClass();

    Returns:
    The Class object that represents the runtime class of this object.
    See Also:
    Literals, section 15.8.2 ofThe Java™ Language Specification.
Class类里有方法getName():

StringgetName()

Returns the name of the entity (class, interface, array class, primitive type, or void) represented by thisClass object, as aString.

测试代码:

public class GetClassTest {/** * 权兴权意-20160907 * @param args */public static void main(String[] args) {// TODO Auto-generated method stubEmployee e = new Employee();Class c = e.getClass();System.out.println(c.getName());//全路径名称:包名.EmployeeSystem.out.println(new int[3][4][5][6][7][8][9].getClass().getName());//[[[[[[[I}}


内部实现:

    /**     * 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.     * @see    <a href="http://java.sun.com/docs/books/jls/">The Java     *         Language Specification, Third Edition (15.8.2 Class     *         Literals)</a>     */    public final native Class<?> getClass();


/**     * Returns the  name of the entity (class, interface, array class,     * primitive type, or void) represented by this <tt>Class</tt> object,     * as a <tt>String</tt>.     *      * <p> If this class object represents a reference type that is not an     * array type then the binary name of the class is returned, as specified     * by the Java Language Specification, Second Edition.     *     * <p> If this class object represents a primitive type or void, then the     * name returned is a <tt>String</tt> equal to the Java language     * keyword corresponding to the primitive type or void.     *      * <p> If this class object represents a class of arrays, then the internal     * form of the name consists of the name of the element type preceded by     * one or more '<tt>[</tt>' characters representing the depth of the array     * nesting.  The encoding of element type names is as follows:     *     * <blockquote><table summary="Element types and encodings">     * <tr><th> Element Type <th>     <th> Encoding     * <tr><td> boolean      <td>     <td align=center> Z     * <tr><td> byte         <td>     <td align=center> B     * <tr><td> char         <td>     <td align=center> C     * <tr><td> class or interface       *                       <td>     <td align=center> L<i>classname</i>;     * <tr><td> double       <td>     <td align=center> D     * <tr><td> float        <td>     <td align=center> F     * <tr><td> int          <td>     <td align=center> I     * <tr><td> long         <td>     <td align=center> J     * <tr><td> short        <td>     <td align=center> S     * </table></blockquote>     *     * <p> The class or interface name <i>classname</i> is the binary name of     * the class specified above.     *     * <p> Examples:     * <blockquote><pre>     * String.class.getName()     *     returns "java.lang.String"     * byte.class.getName()     *     returns "byte"     * (new Object[3]).getClass().getName()     *     returns "[Ljava.lang.Object;"     * (new int[3][4][5][6][7][8][9]).getClass().getName()     *     returns "[[[[[[[I"     * </pre></blockquote>     *     * @return  the name of the class or interface     *          represented by this object.     */    public String getName() {if (name == null)    name = getName0();return name;    }    // cache the name to reduce the number of calls into the VM    private transient String name;    private native String getName0();

关于transient关键字,我们都知道一个对象只要实现了Serilizable接口,这个对象就可以被序列化,java的这种序列化模式为开发者提供了很多便利,我们可以不必关系具体序列化的过程,只要这个类实现了Serilizable接口,这个类的所有属性和方法都会自动序列化。

然而在实际开发过程中,我们常常会遇到这样的问题,这个类的有些属性需要序列化,而其他属性不需要被序列化,打个比方,如果一个用户有一些敏感信息(如密码,银行卡号等),为了安全起见,不希望在网络操作(主要涉及到序列化操作,本地序列化缓存也适用)中被传输,这些信息对应的变量就可以加上transient关键字。换句话说,这个字段的生命周期仅存于调用者的内存中而不会写到磁盘里持久化。

总之,java 的transient关键字为我们提供了便利,你只需要实现Serilizable接口,将不需要序列化的属性前添加关键字transient,序列化对象的时候,这个属性就不会序列化到指定的目的地中。













0 0
原创粉丝点击