指定された文字列が正しい必要があると仮定して、指定された型に従って文字列をキャストする以下のメソッドがあります。
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 を使用し、戻り値の前にキャストしないと、メソッドの外では問題なく動作しますが、これは十分に一般的ではないと思います。
助けてくれてありがとう。