//package com.nowjava;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;/*时 代 J a v a 公 众 号*/
import java.lang.reflect.Modifier;
public class Main {
public static void main(String[] argv) throws Exception {
Class clazz = String.class;
System.out.println(construct(clazz));
}
/**
* Call default private or public constructor.
*
* @param clazz class
* @return new instance
* @throws ReflectiveOperationException reflection exception
*/
public static <T> T construct(final Class<T> clazz)
throws ReflectiveOperationException {
final Constructor<T> constructor = getDeclaredConstructor(clazz);
final boolean isPrivate = Modifier
.isPrivate(getModifiers(constructor));
if (isPrivate) {
setAccessible(constructor, true);/* from 时 代 J a v a 公 众 号*/
}
return getNewInstance(constructor);
}
private static <T> Constructor<T> getDeclaredConstructor(
final Class<T> clazz) throws NoSuchMethodException,
SecurityException {
return clazz.getDeclaredConstructor();
}
private static <T> int getModifiers(final Constructor<T> constructor) {
return constructor.getModifiers();
}
private static void setAccessible(final Constructor<?> constructor,
final boolean value) {
constructor.setAccessible(value);
/**代码未完, 请加载全部代码(NowJava.com).**/
本文系作者在时代Java发表,未经许可,不得转载。如有侵权,请联系nowjava@qq.com删除。