Skip to content

Instantly share code, notes, and snippets.

@tauty
Created February 24, 2014 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tauty/9181486 to your computer and use it in GitHub Desktop.
Save tauty/9181486 to your computer and use it in GitHub Desktop.
newInstance even if the class object specified represent of anonymous class.
package com.github.tauty.rufa;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Util {
public static <T> T newInstance(Class<T> clazz) {
try {
return generate(getConstructor(clazz));
} catch (NoSuchMethodException ignore) {
}
try {
Class<?> enclosingClass = clazz.getEnclosingClass();
return generate(getConstructor(clazz, enclosingClass),
newInstance(enclosingClass));
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("The class, '" + clazz.getName()
+ "', must have default constructor.", e);
}
}
private static <T> Constructor<T> getConstructor(Class<T> clazz,
Class<?>... paramClasses) throws NoSuchMethodException {
try {
return clazz.getDeclaredConstructor(paramClasses);
} catch (SecurityException e) {
throw new WrapException(e);
}
}
private static <T> T generate(Constructor<T> c, Object... params) {
try {
boolean accessible = c.isAccessible();
c.setAccessible(true);
T instance = c.newInstance(params);
c.setAccessible(accessible);
return instance;
} catch (SecurityException e) {
throw new WrapException(e);
} catch (InstantiationException e) {
throw new WrapException(e);
} catch (IllegalAccessException e) {
throw new WrapException(e);
} catch (IllegalArgumentException e) {
throw new WrapException(e);
} catch (InvocationTargetException e) {
throw new WrapException(e);
}
}
public static void main(String[] args) {
System.out.println(newInstance(StaticInner.class));
System.out.println(newInstance(Inner.class));
Runnable runnable = new Runnable() {
public void run() {
Runnable executor = new Runnable() {
public void run() {
}
};
System.out.println(newInstance(executor.getClass()));
}
};
System.out.println(newInstance(runnable.getClass()));
runnable.run();
}
private static class StaticInner {
}
private class Inner {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment