【问题标题】:How can I compare primitive class types? Like Integer and Void?如何比较原始类类型?像整数和虚空?
【发布时间】:2013-05-25 20:54:42
【问题描述】:

我想将方法​​的返回类型与 intvoidString 等类进行比较。

我使用了这样的代码:

它总是打印"null"

Class type = m.getReturnType(); 
if (type.equals(Integer.class)) {
    System.out.print("0");
} else if (type.equals(Long.class)) {
    System.out.print("1");
} else if (type.equals(Boolean.class)) {
    System.out.print("2");
} else if (type.equals(Double.class)) {
    System.out.print("3");
} else if (type.equals(Void.class)) {
    System.out.print("4");
} else {
    System.out.print("null");
}

【问题讨论】:

    标签: java class types


    【解决方案1】:

    您的代码看起来不错,但有一点问题:

    Class type = m.getReturnType(); 
    boolean result = type.equals(Integer.class);
    

    如果m 的返回类型是Integer 类,这里的result 只会计算为true

    如果是 int,则评估结果为 false

    要检查返回类型是否也是原始类型,您需要与Integer.TYPE(不是.class)进行比较,并且与其他类型类似。


    所以改变你的代码:

    if (type.equals(Integer.class)) {
    

    if (type.equals(Integer.class) || type.equals(Integer.TYPE)) {
    

    并对其他类型执行相同的操作。这将匹配 Integer getAge()int getAge() 等方法。

    【讨论】:

      【解决方案2】:

      使用Class.TYPE

      if (type.equals(Integer.TYPE)) {
          ...
      }
      

      由于这是一个java.lang.reflect.Method 类,在这种情况下您不能使用instanceof

      【讨论】:

      • 我也试过这个,但 Eclipse 红色下划线“.class”并写道:令牌“类”上的语法错误,需要标识符“
      • 是的。 m 是一个 java.lang.reflect.Method
      【解决方案3】:

      我猜你是在比较 Wrapper 类型和它们的原始对应物——它们不一样。

      例子:

      interface Methods {
        int mInt();
        Integer mInteger();
      
        void mVoid();
      
      }
      
      class Sample {
        public static void main(String[] args) throws Exception {
          Method mInt = Methods.class.getMethod("mInt", new Class[0]);
          Method mInteger = Methods.class.getMethod("mInteger", new Class[0]);
          Method mVoid = Methods.class.getMethod("mVoid", new Class[0]);
      
      
          mInt.getReturnType(); // returns int.class
          mInteger.getReturnType(); // returns Integer.class
          mVoid.getReturnType(); // returns void.class
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-07
        • 1970-01-01
        • 2012-04-29
        • 2019-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多