提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
调用默认的私有或公共构造函数。
//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.se