java - 将整数转换为长整数

标签 java reflection casting

我需要使用反射来获取字段的值。碰巧我并不总是确定该字段的数据类型是什么。为此,为了避免一些代码重复,我创建了以下方法:

@SuppressWarnings("unchecked")
private static <T> T getValueByReflection(VarInfo var, Class<?> classUnderTest, Object runtimeInstance) throws Throwable {
  Field f = classUnderTest.getDeclaredField(processFieldName(var));
  f.setAccessible(true);
  T value = (T) f.get(runtimeInstance);

  return value;
}

并像这样使用这种方法:

Long value1 = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);

Double[] value2 = getValueByReflection(inv.var2(), classUnderTest, runtimeInstance);

问题是我似乎无法将 Integer 转换为 Long:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

有没有更好的方法来实现这一点?

我使用的是 Java 1.6。

最佳答案

简单地说:

Integer i = 7;
Long l = new Long(i);

关于java - 将整数转换为长整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6690745/

相关文章:

java - Netbeans 错误 : Exception starting filter struts2 ClassNotFoundException: org. apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

基于外部(第三)值的 Java 比较器

reflection - Kotlin 反射 - 检查属性是否具有类型

c# - 如何使 C# 枚举与数据库中的表保持同步

.net - 使用 .Net,我如何确定一个类型是否为 Numeric ValueType?

java.lang.ClassCastException 套接字 readObject

java - 将对象转换为日期

java - 如何比较字符串格式的两个日期?

java - Eclipse,AppEngine : java. lang.RuntimeException : Cannot get the System Java Compiler. 请使用 JDK,而不是 JRE

java - 从 Java 原始 int 转换为 double