首页 > 编程语言 > 详细

Java中,如何让System.out.printf("%d", 2 + 2);输出5

时间:2014-11-17 17:44:43      阅读:327      评论:0      收藏:0      [点我收藏+]

代码如下:

import java.lang.reflect.Field;

public class TwoPlusTwo {
	public static void main(String[] args) throws Exception {
		Class cache = Integer.class.getDeclaredClasses()[0];
		System.out.println(cache.getName());
		Field c = cache.getDeclaredField("cache");
		c.setAccessible(true);
		Integer[] array = (Integer[]) c.get(cache);
		array[132] = array[133];
		System.out.printf("%d", 2 + 2);
	}
}

需要利用反射更改Integer中的缓存,具体步骤:

1. 获取Integer中的内部静态类IntegerCache;

2. 获取cache域;

3. c.setAccessible(true)是取消jvm的变量修饰检查,虽然cache数组是static final类型,我们仍然可以修改其数组元素;

4. 获取数组对象;

5. 数组范围默认是-128到127,阅读源码可知,-128到127之间的、并且通过Integer.valueOf得到的Integer值是直接使用缓存的;cache[132]对应的是Integer(4),可将其修改为Integer(5);

6. System.out.printf的函数接口是PrintStream.printf(String format, Object... args),由于入参为Object,2 + 2会被自动装箱,从而输出Integer.valueOf(4) = cache[132] = cache[133] = 5。

Java中,如何让System.out.printf("%d", 2 + 2);输出5

原文:http://blog.csdn.net/perfect8886/article/details/41212083

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!