java - why parameter.getType().isInstance(HttpServletRequest.class) return is false,but use "==" is true -
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){ //do }else { system.out.println(p.gettype()); system.out.println(p.gettype().isinstance(httpservletrequest.class)); system.out.println(p.gettype() == httpservletrequest.class); } }
the output is:
interface javax.servlet.http.httpservletrequest false true
why use "isinstance" false , use "==" true? because "instance of" can't judge implements relationship?
isinstance equal instanceof
this method dynamic equivalent of java language instanceof operator.
the method return false because comparing class (returned p.gettype()) class httpservletrequest.class instead method want instance example:
dog bobby = new bobbydog(); // class bobbydog extends dog system.out.println(dog.class.isinstance(bobby)); // correct use (return true) system.out.println(dog.class.isinstance(bobbydog.class)); // incorrect use (return false)
the equals operator return true because 2 class equal
p.gettype() == httpservletrequest.class // true httpservletrequest.class == httpservletrequest.class // true
if want judge implements relationship must use method
isassignablefrom(class<?> cls)
determines if class or interface represented class object either same as, or superclass or superinterface of, class or interface represented specified class parameter. returns true if so; otherwise returns false. if class object represents primitive type, method returns true if specified class parameter class object; otherwise returns false.
Comments
Post a Comment