Integer.class vs int.class

前端 未结 4 1182
悲&欢浪女
悲&欢浪女 2020-12-01 05:15

What is the difference between Integer.class, Integer.TYPE and int.class?

acc to me

  1. Integer.class i
4条回答
  •  醉梦人生
    2020-12-01 05:41

    Java handles primitive types versus class types in a schizophrenic way by defining two types for each primitive.

    For instance int is the primitive type and Integer the class type. When you use generics, you are forced to use a non-primitive type so ArrayList is allowed but ArrayList not.

    Since you sometimes want to perform reflection, this duality results in two classes (how else can you inspect a method public int foo ();).

    Say you have a class:

    public class Foo {
    
        private Integer value;
    
        public int value1 () {
            return value;
        }
    
        public Integer value2 () {
            return value;
        }
    
    }
    

    The two methods will not always return the same value, since value2() can return null and value1() will throw a runtime error.

提交回复
热议问题