码迷,mamicode.com
首页 > 编程语言 > 详细

Java基础 ----- 判断对象的类型

时间:2019-08-20 12:34:53      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:https   对象   button   cli   pat   title   function   content   getc   

1、 判断对象的类型:instanceOf 和 isInstance
或者直接将对象强转给任意一个类型,如果转换成功,则可以确定,如果不成功,在异常提示中可以确定类型

public static void main(String[] args) {
        Integer i = new Integer(10);
        System.out.println(i instanceof Integer); // 知道类型名

        String parentClass = "java.lang.String";
        try {
            Class<?> clazz = Class.forName(parentClass);
            String str = new String("111");
            System.out.println(str.getClass().isInstance(clazz.newInstance())); // 不知道类型名,动态加载类型名
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        String str = "222";
        System.out.println((Integer)str);
    }
原文地址:https://blog.csdn.net/miracle_8/article/details/80404537

Java基础 ----- 判断对象的类型

标签:https   对象   button   cli   pat   title   function   content   getc   

原文地址:https://www.cnblogs.com/jpfss/p/11381981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!