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");

PrimitiveType.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 に答える