有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么参数。getType()。isInstance(HttpServletRequest.class)返回值为false,但use“==”为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);
    }
}

输出为:

interface javax.servlet.http.HttpServletRequest
false
true

为什么使用“isInstance”是假的而使用“==”是真的? 因为“实例”不能判断关系


共 (2) 个答案

  1. # 1 楼答案

    isInstance等于instanceOf

    This method is the dynamic equivalent of the Java language instanceof operator.

    该方法返回false,因为您正在将一个类(由p.getType()返回)与另一个类HttpServletRequest进行比较。类。此方法需要一个实例,例如:

    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)
    

    equals运算符返回true,因为这两个类相等

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

    如果你想了解这种关系,你必须使用这种方法

    isAssignableFrom(Class<?> cls) 
    

    Determines if the class or interface represented by this Class object is either the same as, or is a 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 represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

  2. # 2 楼答案

    该类型不是HttpServletRequest类的实例,而是包含HttpServletRequest类信息的^{}实例