Class<MyUtils> adminClass = MyUtils.class;
Constructor<?>[] declaredConstructors = adminClass.getDeclaredConstructors();
Constructor<?> c = declaredConstructors[0];
c.setAccessible(true);// 使其能访问到private构造方法
Object o = c.newInstance();
System.out.println(o);
// 运行报错
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.jiafupeng.controller.rest.UserController.main(UserController.java:59)
Caused by: java.lang.AssertionError: No com.jiafupeng.controller.rest.MyUtils instances for you !
at com.jiafupeng.controller.rest.MyUtils.<init>(MyUtils.java:11)
... 5 more
拓展 可参考 java.util.Objects
代码语言:javascript复制
/**
* This class consists of {@code static} utility methods for operating
* on objects. These utilities include {@code null}-safe or {@code
* null}-tolerant methods for computing the hash code of an object,
* returning a string for an object, and comparing two objects.
*
* @since 1.7
*/
public final class Objects {
private Objects() {
throw new AssertionError("No java.util.Objects instances for you!");
}
...
}