自动包装器
public class AutoBoxingExample {
public static void main(String[] args) {
// 自动装箱示例
int primitiveInt = 10;
// 这里Java自动将int类型的primitiveInt包装成Integer类型
Integer boxedInt = primitiveInt;
System.out.println("自动装箱后的值: " + boxedInt);
// 自动拆箱示例
Integer anotherBoxedInt = new Integer(20);
// 这里Java自动将Integer类型的anotherBoxedInt拆箱成int类型
int anotherPrimitiveInt = anotherBoxedInt;
System.out.println("自动拆箱后的值: " + anotherPrimitiveInt);
// 在集合中使用自动装箱的示例(比如ArrayList)
java.util.ArrayList<Integer> integerList = new java.util.ArrayList<>();
integerList.add(5); // 自动装箱,将int 5包装成Integer后添加到列表
integerList.add(8);
for (Integer element : integerList) {
// 这里遍历的时候自动拆箱,将Integer类型的元素转换为int类型进行操作
System.out.println("集合中的元素(自动拆箱后): " + element);
}
}
}
import java.lang.reflect.Method;
public class GenericAutoWrapper {
public static <T> Object autoBox(Object primitiveValue, Class<T> wrapperClass) {
try {
if (primitiveValue instanceof Integer && wrapperClass == Integer.class) {
return Integer.valueOf((Integer) primitiveValue);
} else if (primitiveValue instanceof Double && wrapperClass == Double.class) {
return Double.valueOf((Double) primitiveValue);
} else if (primitiveValue instanceof Boolean && wrapperClass == Boolean.class) {
return Boolean.valueOf((Boolean) primitiveValue);
}
// 可以继续添加更多基本类型和对应包装类型的处理逻辑
// 如果类型不匹配等情况,可以抛出异常或者返回null等进行提示
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static <T> Object autoUnbox(Object wrapperValue, Class<T> primitiveClass) {
try {
if (wrapperValue instanceof Integer && primitiveClass == int.class) {
return ((Integer) wrapperValue).intValue();
} else if (wrapperValue instanceof Double && primitiveClass == double.class) {
return ((Double) wrapperValue).doubleValue();
} else if (wrapperValue instanceof Boolean && primitiveClass == boolean.class) {
return ((Boolean) wrapperValue).booleanValue();
}
// 同样可以拓展更多类型的处理逻辑
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
int primitiveInt = 15;
Integer boxedInt = (Integer) autoBox(primitiveInt, Integer.class);
System.out.println("通用自动装箱后的值: " + boxedInt);
Integer anotherBoxedInt = new Integer(25);
int anotherPrimitiveInt = (int) autoUnbox(anotherBoxedInt, int.class);
System.out.println("通用自动拆箱后的值: " + anotherPrimitiveInt);
}
}

浙公网安备 33010602011771号