1

我有一个下面的方法根据给定的类型对字符串进行强制转换,假设给定的字符串必须是正确的。

private static <T> T parsePrimitive(final Class<T> primitiveType, final String primitiveValue) {
    if (primitiveType.equals(int.class) || primitiveType.equals(Integer.class)) {
        return primitiveType.cast(Integer.parseInt(primitiveValue));
    }
    /*
    ...
    for the rest of the primitive type
    ...
    */
}

但是,当我打电话时parsePrimitive(int.class, "10");

originalType.cast(Integer.parseInt(primitiveValue));

这导致ClassCastException,对此有任何想法吗?

ps 实际上,当我使用 Object 作为返回类型,并且在返回之前没有强制转换时,它在方法之外可以正常工作,但是我认为这不够通用。

提前感谢您的帮助。

4

2 回答 2

3

您正在混淆自动装箱和铸造。Java 编译器将生成字节码来将您的原语装箱和拆箱到对象,反之亦然,但这不适用于类型。

  • 装箱/拆箱 = 变量
  • 铸造=类型

在您的特定情况下, int.class 和 Integer.class 不能相互分配。

Class<?> intClazz = int.class;
Class<?> integerClazz = Integer.class;
System.out.println(intClazz);
System.out.println(integerClazz);
System.out.println(integerClazz.isAssignableFrom(intClazz));

输出:

int
class java.lang.Integer
false

由于您必须在逻辑中进行大量的专门检查,我不确定尝试提出一种将字符串解析为原始值的通用方法是否值得。

于 2012-04-11T04:20:57.977 回答
0

int.class是一个 VM 内部类,与Integer.class. 下面是一小段代码来展示 int.class 和 Integer.class 之间的区别。

import java.lang.reflect.Modifier;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        dump(int.class);
        System.out.println("---");
        dump(Integer.class);
    }

    private static void dump(Class<?> c) {
        System.out.printf(
            "Name: %s%n" +
            "Superclass: %s%n" +
            "Interfaces: %s%n" +
            "Modifiers: %s%n",
            c.getName(),
            c.getSuperclass() == null ? "null" : c.getSuperclass().getName(),
            Arrays.asList(c.getInterfaces()),
            Modifier.toString(c.getModifiers()));
    }
}

输出:

Name: int
Superclass: null
Interfaces: []
Modifiers: public abstract final
---
Name: java.lang.Integer
Superclass: java.lang.Number
Interfaces: [interface java.lang.Comparable]
Modifiers: public final
于 2012-04-11T04:44:49.840 回答