首页 新闻 会员 周边

关于instance of 与 == 的一点小问题

0
悬赏园豆:80 [待解决问题]
                Parameter[] ps = method.getParameters();
                
                Map<String,Integer> map = new HashMap<String,Integer>();
                
                for(int ij = 0;ij<ps.length;ij++){
                    
                    Parameter p = ps[ij];

                    RequestParam rp = p.getAnnotation(RequestParam.class);
                    
                    if(rp != null){
                        
                       // ...

                    }else {
                        System.out.println();
                        System.out.println(p.getType());
                        System.out.println(p.getType().isInstance(HttpServletRequest.class));
                        System.out.println(p.getType() == HttpServletRequest.class);
                        System.out.println();
                    }
                }

输出的:

interface javax.servlet.http.HttpServletRequest
false
true

为什么isInstance返回的是false,而==返回true?

从输出来看他们的类型是完全相同的。难道是因为HttpServletRequest是个interface?而instance of 不能作用于接口?但是在jdk1.8的api文档(java.lang.Class<T>.isInstance())的介绍中有一句话:   If this Class object represents an interface, this method returns true if the class or any superclass of the specified Object argument implements this interface; it returns false otherwise.更加疑惑不解,求大家帮忙。

山里的小房子的主页 山里的小房子 | 初学一级 | 园豆:122
提问于:2016-06-10 18:36
< >
分享
所有回答(4)
0

isInstance 不是用来检测实例的么。

长蘑菇星人 | 园豆:1832 (小虾三级) | 2016-06-12 08:51
0

Class类的isInstance(Object obj)方法,obj是被测试的对象,如果obj是调用这个方法的class或接口 的实例,则返回true。这个方法是instanceof运算符的动态等价。
形象地:自身类.class.isInstance(自身实例或子类实例)  返回true
例:String s=new String("javaisland");
      System.out.println(String.class.isInstance(s)); //true

大黑 | 园豆:218 (菜鸟二级) | 2016-06-13 11:05
0

isInstance 好像是检查对象是否相等的吧 ==比较的是值

李成祥 | 园豆:204 (菜鸟二级) | 2016-06-13 13:02
0

p对象是Parameter类的实例,isInstance判断成true,说明Parameter肯定是HttpServletRequest的子类。

最好 把倒入的头包给贴出来,不然这些对象 谁知道是什么。

嗜血苏菲 | 园豆:92 (初学一级) | 2016-06-15 14:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册