• Java中9大内置基本数据类型Class实例和数组的Class实例


    1、Java中9大内置几本数据类型:
    对于对象来说,可以直接使用对象.getClass()或者Class.forName(className);类名.class都可以获取Class实例.
    但是我们的基本数据类型,就没有类的权限定名,也没有getClass方法.
    问题:那么如何使用Class类来表示基本数据类型的Class实例?
    byte,short,int,long,char,float,double,boolean,void关键字
    上述8种类型和void关键字,都有class属性.
    表示int的Class对象: Class clz = int.class;
    表示boolean的Class对象: Class clz = boolean.class;
    表示void的Class对象:Class clz = void.class;
    所有的数据类型都有class属性,表示都是Class对象.
    思考:
    int的包装类是Integer
    Integer.class ==?== int.class 相等吗????
    结果是false,说明是两份字节码.

    Integer 和int是同一种数据类型吗? 不是

    但是在八大基本数据类型的包装类中都有一个常量:TYPE,
    TYPE表示的是该包装类对应的基本数据类型的Class实例.
    如:<pre><code>
    Integer.TYPE----->int.class

    Integer.TYPE==int.class;//YES

    Integer.TYPE == Integer.class;//ERROR</pre></code>
    摘自jdk源码:基本数据类型包装类TYPE的实现。

     /** The {@code Class} instance representing the primitive type
     * {@code int}.
     *
     * @since   JDK1.1
     */
    public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
    

    /** Return the Virtual Machine's Class object for the named

    • primitive type.
      */
      static native Class getPrimitiveClass(String name);

2、数组类型的Class实例
每个数组属于被映射为 Class 对象的一个类,所有具有相同元素类型和维数的数组都共享该 Class 对象(摘自JDK原话)。
数组的Class实例:
String[] sArr1 ={"A","C"};
String[] sArr2 = {};
String[][] sArr = {};
int[] sArr = {};
表示数组的Class实例:
String[] sArr1 = {"A","C"};
Class clz = String[].class;//此时clz表示就是一个String类型的一位数组类型

所有具有相同元素类型和维数的数组才共享同一份字节码(Class对象);
注意:和数组中的元素没有一点关系.

eg:<pre><code>
public static void main(String[] args) {

    String[] s1 = {};
    String[] s2 = {"A"};
    String[] s3 = {"A","b"};
    int[] i ={};    
    System.out.println(s1.getClass() == s2.getClass());//true
    System.out.println(s1.getClass() == s3.getClass());//true
    System.out.println(s2.getClass() == s3.getClass());//true
<span class="hljs-built_in">String</span>[][] s4 = {{<span class="hljs-string">"1"</span>,<span class="hljs-string">"2"</span>}};
Class zz = s4.getClass();
System.out.println(s2.getClass() == zz);<span class="hljs-comment">//false</span>
Class zz1 = i.getClass();
System.out.println(s2.getClass() == zz1);<span class="hljs-comment">//false    </span>

}

</pre></code>

原文地址:https://blog.csdn.net/spy19881201/article/details/23995267
  • 相关阅读:
    Datawhale编程实践(LeetCode 腾讯精选练习50)Task2
    Datawhale编程实践(LeetCode 腾讯精选练习50)Task1
    关于深度学习中样本权重取0的问题
    对多维numpy数组使用random.shuffle的问题
    Ubuntu18.04LTS左上角光标闪烁原因之一:NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver.
    pycharm 报错ImportError: could not import module 'PySide2.QtWidgets'
    pyinstaller 打包pyside2项目遇到plugins window问题
    git pull的时候出错: Git Couldn't reserve space for cygwin's heap
    angularjs鼠标移入移出实现显示隐藏
    gulp编译出现Cannot find module 'internal/util/types'——node环境的变更
  • 原文地址:https://www.cnblogs.com/jpfss/p/11382043.html
  • Copyright © 2020-2023  润新知