package org.waabox.bomb;

import java.lang.reflect.Constructor;

import org.objenesis.ObjenesisHelper;

/** Proxy helper that isolates the Proxy generation.
 *
 * Has 2 strategies, the 1st one use sun.misc.Unsafe if could not create the
 * instance, will use Objenesis.
 *
 * @author waabox (waabox[at]gmail[dot]com)
 */
public class Proxy {

  /** The unsafe instance method.*/
  private static Object unsafe;

  static {
    try {
      Class<?> klass = Class.forName("sun.misc.Unsafe");

      if (klass.getMethod("allocateInstance", Class.class) == null) {
        throw new Exception("does not have the allocateInstance method, exit");
      }

      Constructor<?> constructor;
      constructor = klass.getDeclaredConstructor();
      constructor.setAccessible(true);

      unsafe = constructor.newInstance();

    } catch (Exception e) {
      unsafe = null;
    }
  }

  /** Creates a new Proxy for the given class.
   * @param proxyClass the proxy class.
   * @return the object or null.#
   */
  public static Object create(final Class<?> proxyClass) {
    if (unsafe != null) {
      return fromUnsafe(proxyClass);
    } else {
      return fromObjenesis(proxyClass);
    }
  }

  /** Creates a new Proxy instance using {@link Unsafe}.
   * @param proxyClass the Proxy class.
   * @return the instance, or null.
   */
  private static Object fromUnsafe(final Class<?> proxyClass) {
    try {
      return unsafe.getClass().getMethod("allocateInstance", Class.class)
          .invoke(unsafe, proxyClass);
    } catch (Exception e) {
      return null;
    }
  }

  /** Creates a new instance using {@link ObjenesisHelper}.
   * @param proxyClass the Proxy class.
   * @return the instance.
   */
  private static Object fromObjenesis(final Class<?> proxyClass) {
    return ObjenesisHelper.newInstance(proxyClass);
  }

}

@@ -56,16 +56,49 @@
 tructor;
+%0Aimport java.lang.reflect.Method;
 %0A%0Aimport
@@ -398,51 +398,333 @@
 ance
- method.*/%0A  private static Object unsafe;%0A
+, it's Object because some JVM could not have the%0A   * Unsafe class, or could have a protection, etc.%0A   */%0A  private static Object unsafe;%0A%0A  /** The Unsafe method to execute.*/%0A  private static final String UNSAFE_METHOD = %22allocateInstance%22;%0A%0A  /** Checks the existence of the sun.misc.Unsafe and tries to initialize it.*/
 %0A  s
@@ -825,34 +825,29 @@
 tMethod(
-%22allocateInstance%22
+UNSAFE_METHOD
 , Class.
@@ -1714,22 +1714,31 @@
 %7B%0A      
-return
+Method method =
  unsafe.
@@ -1758,34 +1758,29 @@
 tMethod(
-%22allocateInstance%22
+UNSAFE_METHOD
 , Class.
@@ -1789,19 +1789,29 @@
 ass)
+;
 %0A      
-    
+return method
 .inv

Add documentation.