Why result.getType (). isInstance (HttpServletRequest.class) returns false, but using "==" 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 something }else { System.out.println(p.getType()); System.out.println(p.getType().isInstance(HttpServletRequest.class)); System.out.println(p.getType() == HttpServletRequest.class); } } 

output:

 interface javax.servlet.http.HttpServletRequest false true 

why use "isInstance" false and use "==" right? because a “copy” cannot judge the implementation of a relationship?

+5
source share
2 answers

isInstance is equal to instanceOf

This method is the dynamic equivalent of an instance of the Java Operator language.

The method returns false because you are comparing a class (returned by p.getType ()) to another class HttpServletRequest.class, instead this method requires, for example, an instance:

 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 returns true because the two classes are equal

 p.getType() == HttpServletRequest.class // true HttpServletRequest.class == HttpServletRequest.class // true 

If you want the judge to do the relationship, you must use the method

 isAssignableFrom(Class<?> cls) 

Determines whether the class or interface represented by this class object is either the same or is the superclass or superinterface of the class or interface represented by the specified class parameter. It returns true if so; otherwise it returns false. If this class object is a primitive type, this method returns true, if the specified class parameter is this class object; otherwise, it returns false.

+5
source

The type is not an instance of the HttpServletRequest class, it is an instance of java.lang.Class that contains information about the HttpServletRequest class.

+7
source

All Articles