是您无法使用反射来获得对该类的访问权的任何特定原因吗?
我能够做到这一点而没有任何问题,下面是代码:
public static void main(String[] args) throws Exception {Constructor<?> constructor = Class.forName("java.math.MutableBigInteger").getDeclaredConstructor(int.class); constructor.setAccessible(true); Object x = constructor.newInstance(new Integer(17)); Object y = constructor.newInstance(new Integer(19)); Constructor<?> constructor2 = Class.forName("java.math.MutableBigInteger").getDeclaredConstructor(x.getClass()); constructor2.setAccessible(true); Object z = constructor.newInstance(new Integer(0)); Object w = constructor.newInstance(new Integer(0)); Method m = x.getClass().getDeclaredMethod("multiply", new Class[] { x.getClass(), x.getClass()}); Method m2 = x.getClass().getDeclaredMethod("mul", new Class[] { int.class, x.getClass()}); m.setAccessible(true); m2.setAccessible(true); // Slightly faster than BigInteger for (int i = 0; i < 200000; i++) { m.invoke(x, y, z); w = z; z = x; x = w; } // Significantly faster than BigInteger and the above loop for (int i = 0; i < 200000; i++) { m2.invoke(x, 19, x); } BigInteger n17 = new BigInteger("17"); BigInteger n19 = new BigInteger("19"); BigInteger bigX = n17; // Slowest for (int i = 0; i < 200000; i++) { bigX = bigX.multiply(n19); }}编辑:我决定再玩一点,看来java.math.MutableBigInteger的行为与您期望的不完全相同。
当您相乘时,它的运行方式有所不同,当为其分配自身时必须增加内部数组的大小时,它将引发一个异常。我猜是可以预料的。相反,我必须在对象周围进行交换,以便始终将结果放置到其他MutableBigInteger中。经过几千次计算,反射的开销可以忽略不计。随着操作数量的增加,MutableBigInteger最终会领先,并提供越来越好的性能。如果您将“
mul”函数与整数基元用作要乘以的值,则MutableBigInteger的运行速度将比使用BigInteger快10倍。我想这真的归结为您需要乘以什么值。无论哪种方式,如果您将计算结果进行“
1000亿次”



